<?php

namespace Home\Controller;

require_once dirname(__FILE__) . '/../../../../vendor/workerman/gatewayclient/Gateway.php';

use GatewayClient\Gateway;
use Home\Model\TaskDailyModel;
use Think\Controller;

include_once("mysqlha.php");
include_once("Common.php");
header("Content-type:text/html;charset=utf-8");

class PrivatechattestController extends Controller
{
    public function chatList($userid, $first=0, $page=0): array
    {
        $userInfo = M('user')->where(['id'=>$userid])->field('id, sex')->cache(86400)->find();
        $config = M('config_system')->where(['category' => ['in', ['kefu']]])->cache(3600)->getField('title, content');
        $kefu = intval($config['id']);
        if ($first) {
            $page = $page ?: 1;
            $page = ($page - 1) * 20;
            $limit = " limit $page, 20";
        } else {
            $limit = '';
        }
        if($kefu == $userid){
            $sql = <<<sql
                (SELECT *, user_time time FROM chat_lists WHERE user_id = $userid and user_delete = 0 order by user_time desc, id desc)
                UNION (SELECT *, another_time time FROM chat_lists WHERE another_id = $userid and another_delete = 0 order by another_time desc, id desc) order by time desc, id desc $limit
sql;
        }elseif($userInfo['sex'] == '女'){
            $sql = <<<sql
                (SELECT *, user_time time FROM chat_lists WHERE user_id = $userid and user_delete = 0 and user_first = $first order by user_time desc, id desc)
                UNION (SELECT *, another_time time FROM chat_lists WHERE another_id = $userid and another_delete = 0 and another_first = $first order by another_time desc, id desc) order by time desc, id desc $limit
sql;
        }else{
            $sql = <<<sql
                (SELECT *, user_time time FROM chat_lists WHERE user_id = $userid and user_delete = 0 and another_first = $first order by user_time desc, id desc)
                UNION (SELECT *, another_time time FROM chat_lists WHERE another_id = $userid and another_delete = 0 and user_first = $first order by another_time desc, id desc) order by time desc, id desc $limit
sql;
        }

        // var_dump($sql);exit;
        $data = M()->Query($sql);

        if ($data) {
            $gradeNoble = M('grade_noble')->where(['id' => ['gt', 0]])->cache(3600)->getField('id, icon, circle');

            $uids = [];
            foreach ($data as $key => $item) {
                if ($item['user_id'] == $userid) {
                    $uids[] = $item['another_id'];
                } else {
                    $uids[] = $item['user_id'];
                }
            }

            $userstr = implode(',', $uids);
            $users = S('userinfos:'.$userstr);

            if(!$users){
                $users = M('user')->where(['id' => ['in', $uids], 'delete_time' => 0])->getField('id, head_100, name, sex, age, city, is_identity_authentication, noble_grade, noble_time, is_online');
                S('userinfos:'.$userstr, $users, 300);
            }

            $today_start = strtotime(date('Ymd'));
            $time = time();

            $kefus = [];
            $contain1 = [];
            $contain2 = [];
            foreach ($data as $key => $item) {
                $another_id = $item['user_id'] == $userid ? $item['another_id'] : $item['user_id'];

                if (isset($users[$another_id])) {
                    $user = $users[$another_id];

                    $field = $item['user_id'] == $userid ? 'user_' : 'another_';

                    $data[$key]['content'] = $item[$field . 'content'];
                    $data[$key]['userid'] = $item['user_id'] == $userid ? $item['another_id'] : $item['user_id'];
                    $data[$key]['touserid'] = $item['user_id'] == $userid ? $item['another_id'] : $item['user_id'];
                    $data[$key]['type'] = $item[$field . 'channel'];
                    $data[$key]['count'] = $item[$field.'unread'];
                    $data[$key]['isRead'] = $item[$field.'unread'] ? 1 : 0;
                    $data[$key]['sort'] = $item[$field . 'top'] ? $item[$field . 'time'] + 1000000000 : $item[$field . 'time'];
                    $data[$key]['top'] = $item[$field . 'top'];


                    if ($item[$field . 'time'] >= $today_start) {
                        $data[$key]['addtime'] = date('H:i', $item[$field . 'time']);
                    } else if ($item[$field . 'time'] >= ($today_start - 86400)) {
                        $data[$key]['addtime'] = '昨天';
                    } else {
                        $data[$key]['addtime'] = date('Y/m/d', $item[$field . 'time']);
                    }

                    $data[$key]['is_cluster'] = 0;
                    $data[$key]['cluster_types'] = 0;
                    $data[$key]['noble_circle'] = '';

                    if ($user['noble_grade'] && $user['noble_time'] > $time) {
                        $data[$key]['noble_icon'] = $gradeNoble[$user['noble_grade']] ? changeUrl($gradeNoble[$user['noble_grade']]['icon']) : '';
                    } else {
                        $data[$key]['noble_icon'] = '';
                    }

                    $data[$key]['name'] = $user['name'];
                    $data[$key]['sex'] = $user['sex'];
                    $data[$key]['age'] = $user['age'];
                    $data[$key]['is_online'] = $user['is_online'];
                    $data[$key]['kefu'] = $user['id'] == $kefu ? 1 : 0;
                    $data[$key]['is_identity_authentication'] = $user['is_identity_authentication'];
                    $data[$key]['sumb_headimg'] = $user['head_100'];
                    $data[$key]['city'] = '';
                    $data[$key]['intimate'] = 0;

                    unset($data[$key]['another_id'], $data[$key]['user_content'], $data[$key]['another_content'], $data[$key]['user_channel'], $data[$key]['another_channel'],
                        $data[$key]['user_unread'], $data[$key]['another_unread'], $data[$key]['user_untip'], $data[$key]['another_untip'], $data[$key]['user_delete'],
                        $data[$key]['another_delete'], $data[$key]['user_top'],$data[$key]['user_time'], $data[$key]['another_time'], $data[$key]['user_id'],
                        $data[$key]['another_top'], $data[$key]['time'], $data[$key]['user_first'], $data[$key]['another_first']);

                    if ($userid == $kefu) {
                        if ($user['id'] == $kefu) {
                            $item['city'] = '';
                            $kefus[] = $data[$key];
                        } else if (!$data[$key]['is_cluster'] && $data[$key]['touserid'] == $kefu) {
                            $contain1[] = $data[$key];
                        } else {
                            $contain2[] = $data[$key];
                        }
                    } else {
                        $contain2[] = $data[$key];
                    }
                }
            }

            array_multisort(array_column($kefus, 'sort'), SORT_DESC, $kefus);
            array_multisort(array_column($contain1, 'sort'), SORT_DESC, $contain1);
            array_multisort(array_column($contain2, 'sort'), SORT_DESC, $contain2);

            $data = array_merge($kefus, $contain1, $contain2);
            
            if (count($data) > 150) {
                $output = array_slice($data, 150);
    
                $update_user = [];
                $update_another = [];
                foreach ($output as $item) {
                    if ($item['userid'] > $userid) {
                        $update_user[] = $item['id'];
                    } else {
                        $update_another[] = $item['id'];
                    }
                }
                
                if ($update_user) {
                    M('chat_lists')->where(['id' => ['in', $update_user]])->save(['user_unread' => 0, 'user_delete' => 1]);
                }
                if ($update_another) {
                    M('chat_lists')->where(['id' => ['in', $update_another]])->save(['another_unread' => 0, 'another_delete' => 1]);
                }
            }

            return $data;
        } else {
            return [];
        }
    }

    public function getreadcount($data)
    {
        $data = json_decode($data, true);

        $user_id = $data['user_id'];
    
        $user = M('user')->field('sex, register_datetime')->cache(86400)->where(['id' => $user_id])->find();

        //$untip1 = M('privatechat')->where(['touserid' => $user_id, 'sound_tip' => 0, 'status' => ['neq', -1], 'isRead' => 0])->count(); # 私聊声音提示
        //$unread1 = M('privatechat')->where(['touserid' => $user_id, 'isRead' => 0, 'status' => ['neq', -1]])->count(); # 私聊未读消息数

        $sql = <<<sql
            (SELECT sum(user_untip) untip FROM chat_lists WHERE user_id = $user_id and user_delete = 0) 
            UNION (SELECT sum(another_untip) untip FROM chat_lists WHERE another_id = $user_id and another_delete = 0)
sql;
        $chat_lists = M()->Query($sql);
        $untip1 = $chat_lists[0]['untip'] + $chat_lists[1]['untip'];

        $sql = <<<sql
            (SELECT sum(user_unread) unread FROM chat_lists WHERE user_id = $user_id and user_delete = 0) 
            UNION (SELECT sum(another_unread) unread FROM chat_lists WHERE another_id = $user_id and another_delete = 0)
sql;
        $chat_lists = M()->Query($sql);

        $unread1 = $chat_lists[0]['unread'] + $chat_lists[1]['unread'];
    
        $channel = $user['sex'] == '男' ? [1,2] : [1,3];
        $where = ['channel' => ['in', $channel], 'type' => 0];
        $where['_string'] = "is_top = 1 or create_time >= '" . $user['register_datetime'] . "'";
        $message = M('sys_message')->where($where)->order('is_top desc, id desc')->limit(20)->getField('id', true);
    
        if ($message) {
            $read_count = M('sys_message_read')->where(['user_id' => $user_id, 'message_id' => ['in', $message]])->count();
            $unread2 = count($message) - $read_count;
        } else {
            $unread2 = 0;
        }

        $sound_tip = $untip1;
        if ($sound_tip) {
            //M('privatechat')->where(['touserid' => $user_id])->save(['sound_tip' => 1]);

            M('chat_lists')->where(['user_id' => $user_id])->save(['user_untip' => 0]);
            M('chat_lists')->where(['another_id' => $user_id])->save(['another_untip' => 0]);

            $code = 200;
            $message = 1;
        } else {
            $code = 400;
            $message = 0;
        }

        $message = json_encode([
            "code" => $code,
            "action" => 'Home/Privatechat/getreadcount',
            'data' => [
                "message" => $message,
                "chat_count" => (int)$unread1,
                'message_count' => $unread2
            ]
        ]);

        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user_id, $message);
    }

    public function changeread($user_id, $touserid)
    {
        M('privatechat')->where(['userid' => $touserid, 'touserid' => $user_id])->save(['isRead' => 1]);

        // 更新会话列表
        D('ChatLists')->changeLists($user_id, $touserid);

        // 清除聊天缓存
        /*S("getMsgList$user_id&$touserid",null);
        S("getMsgList$touserid&$user_id",null);*/

        $message = json_encode(['code' => 200, 'action' => 'Home/Privatechat/changeread', 'data' => ['touserid' => $user_id]]);

        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, $message);
    }

    public function changecount($user_id, $touserid)
    {
        /*M('privatechat')->where(['userid' => $touserid, 'touserid' => $user_id])->save(['isCount' => 1]);

        echo '{"code":"200"}';*/
    }

    //获取开始的20条信息
    public function getMsgList()
    {
        $userid = I('userid');
        $touserid = I('touserid');
        $page = I('page') ?: 0;
        $pages = I('pages') ?: 20;


        $start = $page * $pages;

        $lastTime = time();

        $Model = M('privatechat');

        $users = M('user')->where(['id' => ['in', [$userid, $touserid]]])->cache(3600)->getField('id, name, head_100 head_portrait, sex');

        $sql = <<<sql
        (select id, type, userid, content, isRead, is_burn, second, status, state, data, k, score, finish, location,addtime  from privatechat
        where userid = $userid and touserid = $touserid and single <> 1 and status not in (-1,1))
        union all
        (select id, type, userid, content, isRead, is_burn, second, status, state, data, k, score, finish, location,addtime  from privatechat
        where userid = $touserid and touserid = $userid and status not in (-1,2))
        order by id desc limit $start, $pages
sql;

        $data = $Model->Query($sql);

        if ($data) {
            $updates = [];
            foreach ($data as $key => $item) {
                if (!$item['isRead'] && $item['userid'] != $userid) {
                    $updates[] = $item['id'];
                }

                $data[$key]['name'] = $users[$item['userid']]['name'];
                $data[$key]['head_portrait'] = $users[$item['userid']]['head_portrait'];

                $data[$key]['self'] = $item['userid'] == $userid ? 1 : 0;

                $data[$key]['showtime'] = $lastTime - strtotime($item['addtime']) > 300;
                $lastTime = strtotime($item['addtime']);
                $data[$key]['timestamp'] = $lastTime;

                $data[$key]['time'] = timeTodate(strtotime($item['addtime']));


                $data[$key]['type'] = $item['type'] == -2 ? 0 : $item['type'];

                $datas = json_decode($item['data'], true);
                if (isset($datas['image'])) {
                    $datas['image'] = changeUrl($datas['image']);
                }

                $datas['cover'] = $datas['cover'] ?? '';
                $data[$key]['data'] = $datas;

                if (in_array($item['type'], [9, 10])) {
                    if (isset($datas['status']) && $datas['status']) {
                        if (isset($datas['start']) && isset($datas['end'])) {
                            $chat_time = $datas['end'] - $datas['start'];
                            $data[$key]['chat_time'] = changeTime($chat_time);
                        } else {
                            if ($datas['second']) {
                                $data[$key]['content'] .= changeTime($datas['second'] * 60);
                            } else {
                                $data[$key]['content'] .= '01:00';
                            }
                        }
                    } else {
                        $data[$key]['content'] .= ' 未接通';
                    }
                } else if ($item['type'] == 11) {
                    $data[$key]['content'] = changeUrl($item['content']);
                }
            }

            $ids = array_column($data, 'id');
            array_multisort($ids,SORT_ASC,$data);



            if ($updates) {
                $Model->where(['id' => ['in', $updates]])->setField('isRead', 1);

                if ($data) {
                    if ($userid != 5559516 && $touserid != 5559516 && $users[$userid]['sex'] == '男' && $users[$touserid]['sex'] == '女') {
                        $data_count = count($ids);
                        if ($data_count == 1 || (isset($data[$data_count - 1]['showtime']) && $data[$data_count - 1]['showtime'])) {
                            $contain_tip = ['userid' => $userid, 'touserid' => $touserid, 'type' => -1, 'single' => 1, "content" => '对方查看了你的消息', 'finish' => 1, 'is_public' => 1];
                            M('privatechat')->add($contain_tip);
                            // 更新会话列表
                            D('ChatLists')->updateLists($userid, $touserid, 1, -1, '对方查看了你的消息');
                            $this->getOtherList(json_encode(['userid' => $touserid, 'count' => '', 'type' => '']));
                        }
                    }
                }
            }
        }

        // 更新会话列表
        D('ChatLists')->changeLists($userid, $touserid);

        exit(getSuccessJson([$data]));
    }

    //获取信息列表
    public function getOtherList($data)
    {
        $data = json_decode($data, true);

        $userid = $data['userid'];
        $oldcount = $data['count'] ?? '';
        $type = $data['type'] ?? '';
        $friend = $data['friend'] ?? 0;

        $chat_lists_records = M('chat_lists_records')->where(['user_id' => $userid])->find();

        if ($chat_lists_records) {
            $result = $this->chatList($userid);

            $data = json_encode(['code' => 200, 'action' => 'Home/Privatechat/getOtherList', 'data' => ['result' => $result, 'count' => 0]]);
        } else {
            $isfan = false;

            $Model = M();

            $allcount = 0;

            $config = M('config_system')->where(['category' => ['in', ['kefu', 'family', 'user']]])->cache(86400)->getField('title, content');

            $user = M('user')->field('sex')->where(['id' => $userid])->find();
            if ($user['sex'] == '女' && $userid != $config['id']) {
                $unread_uid = M('privatechat')->where(['type' => ['neq', -1], 'single' => ['neq', 1], 'userid' => $userid, 'isRead' => 0, 'is_fate' => 1])->getField('touserid', true);
                $map['_string'] = '(type <> -1 or is_public = 1) and (single <> 1 or is_public = 1)';
                $map['userid'] = ['in', $unread_uid];
                $map['touserid'] = $userid;
                $chat_uid = M('privatechat')->where($map)->getField('userid', true);
                $chat_uid = $chat_uid ?: [];
                $not_reply = implode(',', array_diff($unread_uid, $chat_uid)) ?: 0;

                $sql = <<<sql
            (SELECT userid, MAX(id) AS id FROM privatechat WHERE (type <> -1 or is_public = 1) and userid not in ($not_reply) and touserid = $userid and status <> -1 GROUP BY userid)
            UNION (SELECT touserid,MAX(id) AS id FROM privatechat WHERE (type <> -1 or is_public = 1) and single <> 1 and userid = $userid and touserid not in ($not_reply) and status <> -1 GROUP BY touserid)
sql;

            } else {
                $sql = <<<sql
            (SELECT userid, MAX(id) AS id FROM privatechat WHERE (type <> -1 or is_public = 1) and touserid = $userid and status <> -1 GROUP BY userid)
            UNION (SELECT touserid,MAX(id) AS id FROM privatechat WHERE (type <> -1 or is_public = 1) and single <> 1 and userid = $userid and status <> -1 GROUP BY touserid)
sql;
            }

            $result = $Model->Query($sql);



            // 家族
            $gresult = [];
            if (intval($config['family_switch'])) {
                $sql = "select t.*, t1.name, t1.logo sumb_headimg from cluster_user t, cluster t1 where t.user_id = $userid and t1.types = 1 and t.status = 1 and t1.id = t.cluster_id";
                $glist = $Model->Query($sql);

                $cluster_ids = array_column($glist, 'cluster_id');

                $clusterChats = M('clusterchat')->where(['cluster_id' => ['in', $cluster_ids]])->getField('cluster_id, id, type, content, addtime');
                $talkcounts = M('clusterchat')->where(['cluster_id' => ['in', $cluster_ids]])->group('cluster_id')->getField('cluster_id, count(*) count');

                for ($i = 0; $i < sizeof($glist); $i++) {
                    $talkcount = $talkcounts[$glist[$i]['cluster_id']] ?? 0;

                    if ($talkcount > 0) {
                        $glist[$i]['is_cluster'] = 1;
                        $glist[$i]['cluster_types'] = 1;

                        $talkone = $clusterChats[$glist[$i]['cluster_id']];

                        $glist[$i]['kefu'] = 0;
                        $glist[$i]['id'] = $talkone['id'];
                        $glist[$i]['touserid'] = $talkone['cluster_id'];
                        $glist[$i]['content'] = $talkone['content'];
                        $glist[$i]['sort_field'] = strtotime($talkone['addtime']);
                        $glist[$i]['addtime'] = time_tran($talkone['addtime']);

                        $count2 = $Model->Query("select count(*) as count from clusterchat where cluster_id=" . $glist[$i]['cluster_id'] . " and find_in_set($userid, isRead)");

                        $count = $talkcount - $count2[0]['count'];

                        if ($count > 0) {
                            $isfan = true;
                        }
                        $allcount = $allcount + $count;
                        $glist[$i]['count'] = $count;

                        $channel = [1 => '[图片]', 2 => '[语音]', 3 => '[视频]', 6 => '[位置]', 8 => '[礼物]', 11 => '[表情]'];

                        if (isset($channel[$talkone['type']])) {
                            $glist[$i]['content'] = $channel[$talkone['type']];
                        }

                        array_push($gresult, $glist[$i]);
                    }
                }
            }


            $kefu = intval($config['id']);

            $ids = array_column($result, 'id');
            $uids = array_column($result, 'userid');
            $chats = M('privatechat')->where(['id' => ['in', $ids]])->cache(86400)->getField('id, content, userid, touserid, status, state, type, isRead, addtime');
            $users = M('user')->where(['id' => ['in', $uids], 'delete_time' => 0])->getField('id, head_100, name, sex, age, city, is_identity_authentication, noble_grade, noble_time, is_online');
            //$personals = M('config_personal')->where(['user_id' => ['in', $uids]])->getField('user_id, hide_distance, id');
            $delChat = M('del_chat')->where(['uid' => $userid])->getField('to_uid', true);
            $gradeNoble = M('grade_noble')->where(['id' => ['gt', 0]])->cache(86400)->getField('id, icon, circle');

            $userIds = [];
            foreach ($result as $k => $v) {
                $userIds[] = $v['userid'] == $userid ? $v['touserid'] : $v['userid'];
            }

            $map['_string'] = 'type <> -1 or is_public = 1';
            $map['userid'] = ['in', $userIds];
            $map['touserid'] = $userid;
            $map['status'] = ['not in', [-1,2]];
            $map['isRead'] = 0;
            $counts = M('privatechat')
                //->where(['type' => ['neq', -1], 'userid' => ['in', $userIds], 'touserid' => $userid, 'status' => ['not in', [-1,2]], 'isRead' => 0])
                ->where($map)
                ->group('userid, touserid')
                ->getField('CONCAT_WS("+", userid, touserid), COUNT(*) AS count');

            $del = [];
            foreach ($result as $k => $v) {
                if (in_array($v['userid'], $delChat)) {
                    unset($result[$k]);
                } else {
                    if (isset($users[$v['userid']]) && isset($chats[$v['id']])) {
                        /*if ($userid == $kefu && $users[$v['userid']]['sex'] == '男') {
                            unset($result[$k]);
                            continue;
                        }*/

                        $chat = $chats[$v['id']];
                        $user = $users[$v['userid']];

                        $sql = $userid == $chat['userid'] ? ' and single <> 1 ' : '';

                        if ($v['userid'] == $userid) {
                            $count = $counts[$v['touserid'] . '+' . $userid]['count'] ?? 0;
                        } else {
                            $count = $counts[$v['userid'] . '+' . $userid]['count'] ?? 0;
                        }

                        $result[$k]['content'] = $chat['content'];
                        $result[$k]['touserid'] = $chat['touserid'];
                        $result[$k]['status'] = $chat['status'];
                        $result[$k]['state'] = $chat['state'];
                        $result[$k]['type'] = $chat['type'];
                        $result[$k]['sort_field'] = strtotime($chat['addtime']);
                        //$result[$k]['addtime'] = strtotime($chat['addtime']) >= strtotime(date('Ymd')) ? date('H:i', strtotime($chat['addtime'])) : $chat['addtime'];

                        if (strtotime($chat['addtime']) >= strtotime(date('Ymd'))) {
                            $result[$k]['addtime'] = date('H:i', strtotime($chat['addtime']));
                        } else if (strtotime($chat['addtime']) >= (strtotime(date('Ymd')) - 86400)) {
                            $result[$k]['addtime'] = '昨天';
                        } else {
                            $result[$k]['addtime'] = date('Y/m/d', strtotime($chat['addtime']));
                        }
                        $result[$k]['name'] = $user['name'];
                        $result[$k]['sex'] = $user['sex'];
                        $result[$k]['age'] = $user['age'];
                        $result[$k]['is_online'] = $user['is_online'];

                        /*if (isset($personals[$v['userid']]['hide_distance']) && $personals[$v['userid']]['hide_distance']) {
                            $result[$k]['city'] = '';
                        } else {
                            $result[$k]['city'] = $user['city'];
                        }

                        if ($config['hide_city'] && $user['sex'] == '女') {
                            $result[$k]['city'] = '';
                        }*/

                        $result[$k]['city'] = '';

                        if ($user['noble_grade'] && $user['noble_time'] > time()) {
                            $result[$k]['noble_circle'] = $gradeNoble[$user['noble_grade']] ? $gradeNoble[$user['noble_grade']]['circle'] : '';
                        } else {
                            $result[$k]['noble_circle'] = '';
                        }

                        $result[$k]['kefu'] = $user['id'] == $kefu ? 1 : 0;
                        $result[$k]['is_identity_authentication'] = $user['is_identity_authentication'];
                        $result[$k]['sumb_headimg'] = $user['head_100'];
                        $result[$k]['count'] = $count;
                        $result[$k]['isRead'] = $chat['isRead'];
                        $result[$k]['is_cluster'] = 0;
                        $result[$k]['cluster_types'] = 0;


                        if ($user['noble_grade'] && $user['noble_time'] > time()) {
                            $result[$k]['noble_icon'] = $gradeNoble[$user['noble_grade']] ?? '';
                        } else {
                            $result[$k]['noble_icon'] = '';
                        }

                        $allcount = $allcount + $count;

                        $channel = [1 => '[图片]', 2 => '[语音]', 3 => '[视频]', 6 => '[位置]', 8 => '[礼物]', 11 => '[表情]'];

                        if (isset($channel[$result[$k]['type']])) {
                            $result[$k]['content'] = $channel[$result[$k]['type']];

                            if ($result[$k]['type'] == 11) {
                                $result[$k]['content'] = changeUrl($result[$k]['content']);
                            }
                        } else if ($result[$k]['type'] == -1) {
                            switch ($result[$k]['status']) {
                                case 0:
                                    if ($result[$k]['state'] == 1) {
                                        if ($chat['userid'] != $userid) {
                                            $name = M('user')->where(['id' => $chat['userid']])->getField('name');
                                            $result[$k]['content'] = '"' . $name . '"领取了你的红包';
                                        } else {
                                            $name = M('user')->where(['id' => $chat['touserid']])->getField('name');
                                            $result[$k]['content'] = '你已领取"' . $name . '"的红包';
                                        }
                                    }
                                    break;
                                case 3:
                                    if ($chat['userid'] == $userid) {
                                        $result[$k]['content'] = '你撤回了一条消息';
                                    } else {
                                        $name = M('user')->where(['id' => $chat['userid']])->getField('name');
                                        $result[$k]['content'] = '"' . $name . '"撤回了一条消息';
                                    }
                                    break;
                            }
                        } else {
                            if ($result[$k]['single']) {
                                if ($user[0]['sex'] == '男') {
                                    $result[$k]['content'] = '[回复消息得奖励]';
                                }
                            } else {
                                if (in_array($result[$k]['type'], [5, 7]) && in_array($result[$k]['state'], [0, 2])) {
                                    $result[$k]['content'] = '[红包]' . $result[$k]['content'];
                                }
                                switch ($result[$k]['status']) {
                                    case 1:
                                        if ($chat['userid'] == $userid) {
                                            $result[$k]['content'] = '[消息已删除]';
                                        }
                                        break;
                                    case 2:
                                        if ($chat['touserid'] == $userid) {
                                            $result[$k]['content'] = '[消息已删除]';
                                        }
                                        break;
                                    default :
                                        break;
                                }
                            }
                        }
                    } else {
                        unset($result[$k]);

                        $del[] = $v['userid'];
                    }
                }
            }

            if ($del) {
                //M('privatechat')->where(['userid|touserid' => ['in', $del]])->delete();
            }

            if ($type == 0 || $allcount != $oldcount) {
                $result = array_merge($result, $gresult);

                // 去除重复项，将最新聊天顶上去
                if ($result) {
                    array_multisort(array_column($result, 'sort_field'), SORT_DESC, $result);

                    $con = [];
                    $arr = [];
                    foreach ($result as $k => $v) {
                        if (!in_array($v['userid'], $arr)) {
                            $con[$k] = $v;
                            $arr[$k] = $v['userid'];

                            $con[$k]['top'] = 0;
                            $con[$k]['sort'] = 0;
                        }
                    }
                    $result = array_values($con);

                    $tops_chat = M('top_chat')->where(['types' => 1, 'uid' => $userid])->order('id asc')->getField('to_uid', true);
                    //$tops_cluster = M('top_chat')->where(['types' => 2, 'uid' => $userid])->order('id asc')->getField('to_uid', true);
                    $tops_cluster = [];

                    if ($tops_chat || $tops_cluster) {
                        $con1 = [];
                        $con2 = [];
                        foreach ($result as $k => $v) {

                            $tops = $v['is_cluster'] ? $tops_cluster : $tops_chat;

                            if ($v['is_cluster']) {
                                $tops = $tops_cluster;
                                $tops_field = 'cluster_id';
                            } else {
                                $tops = $tops_chat;
                                $tops_field = 'userid';
                            }

                            if (in_array($v[$tops_field], $tops)) {
                                $v['top'] = 1;
                                $v['sort'] = array_search($v[$tops_field], $tops);
                                $con1[] = $v;
                            } else {
                                $con2[] = $v;
                            }
                        }

                        if ($con1) {
                            $tmp = array_column($con1, 'sort');
                            array_multisort($tmp, SORT_DESC, $con1);
                        }

                        $result = array_merge($con1, $con2);
                    }
                }

                //array_multisort(array_column($result, 'addtime'), SORT_DESC, $result);

                if ($userid != $kefu) {
                    $kefus = [];
                    $contain1 = [];
                    $contain2 = [];
                    foreach ($result as $key => $item) {
                        if ($item['kefu']) {
                            $item['city'] = '';
                            $kefus[] = $item;
                        } else if (!$item['is_cluster'] && $item['touserid'] == $kefu) {
                            $contain1[] = $item;
                        } else {
                            $contain2[] = $item;
                        }
                    }

                    $result = array_merge($kefus, $contain1, $contain2);
                }

                foreach ($result as $key => $item) {
                    /*$intimate = M('user_intimate')->where(['couple_a|couple_b' => $item['touserid'] . ',' . $userid, 'intimate' => ['gt', 0]])->getField('intimate');

                    $result[$key]['intimate'] = $intimate ?: 0;*/

                    $result[$key]['intimate'] = 0;
                }

                $data = json_encode(['code' => 200, 'action' => 'Home/Privatechat/getOtherList', 'data' => ['result' => $result, 'count' => $allcount]]);
            } else {
                $data = json_encode(['code' => 400, 'action' => 'Home/Privatechat/getOtherList', 'data' => []]);
            }

            // 更新会话列表
            D('ChatLists')->synchLists($userid, $result);
        }

        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $userid, $data);
    }

    // 未回复列表
    public function notReplyList($data='', $userid, $page=1)
    {
        $data = json_decode($data, true);

        $oldcount = $data['count'] ?? '';
        $type = $data['type'] ?? '';
        $friend = $data['friend'] ?? 0;

        $isfan = false;

        $Model = M();

        $allcount = 0;

        // $page = ($page - 1) * 10;

        $result = $this->chatList($userid, 1, $page);

        exit(json_encode(['code' => 200, 'data' => $result]));

    
        $unread_uid = M('privatechat')->where(['type' => ['neq', -1], 'single' => ['neq', 1], 'userid' => $userid, 'isRead' => 0, 'is_fate' => 1])->getField('touserid', true);
        $map['_string'] = '(type <> -1 or is_public = 1) and (single <> 1 or is_public = 1)';
        $map['userid'] = ['in', $unread_uid];
        $map['touserid'] = $userid;
        $chat_uid = M('privatechat')->where($map)->getField('userid', true);
        $chat_uid = $chat_uid ?: [];
        $not_reply = implode(',', array_diff($unread_uid, $chat_uid)) ?: 0;

        $sql = <<<sql
            (SELECT userid, MAX(id) AS id FROM privatechat WHERE type <> -1 and userid in ($not_reply) and touserid = $userid and status <> -1 GROUP BY userid)
            UNION (SELECT touserid,MAX(id) AS id FROM privatechat WHERE type <> -1 and single <> 1 and userid = $userid and touserid in ($not_reply) and status <> -1 GROUP BY touserid)
             LIMIT $page,10
sql;
        $result = $Model->Query($sql);

        $config = M('config_system')->where(['category' => ['in', ['kefu', 'family', 'user']]])->getField('title, content');

        // 家族
        $gresult = [];

        $kefu = intval($config['id']);

        $ids = array_column($result, 'id');
        $uids = array_column($result, 'userid');
        $chats = M('privatechat')->where(['id' => ['in', $ids]])->getField('id, content, userid, touserid, status, state, type, isRead, addtime');
        $users = M('user')->where(['id' => ['in', $uids]])->getField('id, head_100, name, sex, age, city, is_identity_authentication, noble_grade, noble_time');
        $delChat = M('del_chat')->where(['uid' => $userid])->getField('to_uid', true);
        $gradeNoble = M('grade_noble')->where(['id' => ['gt', 0]])->cache(86400)->getField('id, icon, circle');

        $userIds = [];
        foreach ($result as $k => $v) {
            $userIds[] = $v['userid'] == $userid ? $v['touserid'] : $v['userid'];
        }

        $counts = M('privatechat')
            ->where(['type' => ['neq', -1], 'userid' => ['in', $userIds], 'touserid' => $userid, 'status' => ['not in', [-1,2]], 'isRead' => 0])
            ->group('userid, touserid')
            ->getField('CONCAT_WS("+", userid, touserid), COUNT(*) AS count');

        $del = [];
        foreach ($result as $k => $v) {
            if (in_array($v['userid'], $delChat)) {
                unset($result[$k]);
            } else {
                if (isset($users[$v['userid']]) && isset($chats[$v['id']])) {
                    $chat = $chats[$v['id']];
                    $user = $users[$v['userid']];

                    $sql = $userid == $chat['userid'] ? ' and single <> 1 ' : '';

                    if ($v['userid'] == $userid) {
                        $count = $counts[$v['touserid'] . '+' . $userid]['count'] ?? 0;
                    } else {
                        $count = $counts[$v['userid'] . '+' . $userid]['count'] ?? 0;
                    }

                    $result[$k]['content'] = $chat['content'];
                    $result[$k]['touserid'] = $chat['touserid'];
                    $result[$k]['status'] = $chat['status'];
                    $result[$k]['state'] = $chat['state'];
                    $result[$k]['type'] = $chat['type'];
                    $result[$k]['sort_field'] = strtotime($chat['addtime']);
                    //$result[$k]['addtime'] = strtotime($chat['addtime']) >= strtotime(date('Ymd')) ? date('H:i', strtotime($chat['addtime'])) : $chat['addtime'];

                    if (strtotime($chat['addtime']) >= strtotime(date('Ymd'))) {
                        $result[$k]['addtime'] = date('H:i', strtotime($chat['addtime']));
                    } else if (strtotime($chat['addtime']) >= (strtotime(date('Ymd')) - 86400)) {
                        $result[$k]['addtime'] = '昨天';
                    } else {
                        $result[$k]['addtime'] = date('Y/m/d', strtotime($chat['addtime']));
                    }
                    $result[$k]['name'] = $user['name'];
                    $result[$k]['sex'] = $user['sex'];
                    $result[$k]['age'] = $user['age'];

                    /*if (isset($personals[$v['userid']]['hide_distance']) && $personals[$v['userid']]['hide_distance']) {
                        $result[$k]['city'] = '';
                    } else {
                        $result[$k]['city'] = $user['city'];
                    }

                    if ($config['hide_city'] && $user['sex'] == '女') {
                        $result[$k]['city'] = '';
                    }*/

                    $result[$k]['city'] = '';

                    if ($user['noble_grade'] && $user['noble_time'] > time()) {
                        $result[$k]['noble_circle'] = $gradeNoble[$user['noble_grade']] ? $gradeNoble[$user['noble_grade']]['circle'] : '';
                    } else {
                        $result[$k]['noble_circle'] = '';
                    }

                    $result[$k]['kefu'] = $user['id'] == $kefu ? 1 : 0;
                    $result[$k]['is_identity_authentication'] = $user['is_identity_authentication'];
                    $result[$k]['sumb_headimg'] = $user['head_100'];
                    $result[$k]['count'] = $count;
                    $result[$k]['isRead'] = $chat['isRead'];
                    $result[$k]['is_cluster'] = 0;
                    $result[$k]['cluster_types'] = 0;


                    if ($user['noble_grade'] && $user['noble_time'] > time()) {
                        $result[$k]['noble_icon'] = $gradeNoble[$user['noble_grade']] ?? '';
                    } else {
                        $result[$k]['noble_icon'] = '';
                    }

                    $allcount = $allcount + $count;

                    $channel = [1 => '[图片]', 2 => '[语音]', 3 => '[视频]', 6 => '[位置]', 8 => '[礼物]', 11 => '[表情]'];

                    if (isset($channel[$result[$k]['type']])) {
                        $result[$k]['content'] = $channel[$result[$k]['type']];

                        if ($result[$k]['type'] == 11) {
                            $result[$k]['content'] = changeUrl($result[$k]['content']);
                        }
                    } else if ($result[$k]['type'] == -1) {
                        switch ($result[$k]['status']) {
                            case 0:
                                if ($result[$k]['state'] == 1) {
                                    if ($chat['userid'] != $userid) {
                                        $name = M('user')->where(['id' => $chat['userid']])->getField('name');
                                        $result[$k]['content'] = '"' . $name . '"领取了你的红包';
                                    } else {
                                        $name = M('user')->where(['id' => $chat['touserid']])->getField('name');
                                        $result[$k]['content'] = '你已领取"' . $name . '"的红包';
                                    }
                                }
                                break;
                            case 3:
                                if ($chat['userid'] == $userid) {
                                    $result[$k]['content'] = '你撤回了一条消息';
                                } else {
                                    $name = M('user')->where(['id' => $chat['userid']])->getField('name');
                                    $result[$k]['content'] = '"' . $name . '"撤回了一条消息';
                                }
                                break;
                        }
                    } else {
                        if ($result[$k]['single']) {
                            if ($user[0]['sex'] == '男') {
                                $result[$k]['content'] = '[回复消息得奖励]';
                            }
                        } else {
                            if (in_array($result[$k]['type'], [5, 7]) && in_array($result[$k]['state'], [0, 2])) {
                                $result[$k]['content'] = '[红包]' . $result[$k]['content'];
                            }
                            switch ($result[$k]['status']) {
                                case 1:
                                    if ($chat['userid'] == $userid) {
                                        $result[$k]['content'] = '[消息已删除]';
                                    }
                                    break;
                                case 2:
                                    if ($chat['touserid'] == $userid) {
                                        $result[$k]['content'] = '[消息已删除]';
                                    }
                                    break;
                                default :
                                    break;
                            }
                        }
                    }
                } else {
                    unset($result[$k]);

                    $del[] = $v['userid'];
                }
            }
        }

        if ($del) {
            //M('privatechat')->where(['userid|touserid' => ['in', $del]])->delete();
        }

        if ($type == 0 || $allcount != $oldcount) {
            $result = array_merge($result, $gresult);

            // 去除重复项，将最新聊天顶上去
            if ($result) {
                array_multisort(array_column($result, 'sort_field'), SORT_DESC, $result);

                $con = [];
                $arr = [];
                foreach ($result as $k => $v) {
                    if (!in_array($v['userid'], $arr)) {
                        $con[$k] = $v;
                        $arr[$k] = $v['userid'];

                        $con[$k]['top'] = 0;
                        $con[$k]['sort'] = 0;
                    }
                }
                $result = array_values($con);

                $tops_chat = M('top_chat')->where(['types' => 1, 'uid' => $userid])->order('id asc')->getField('to_uid', true);
                $tops_cluster = M('top_chat')->where(['types' => 2, 'uid' => $userid])->order('id asc')->getField('to_uid', true);

                if ($tops_chat || $tops_cluster) {
                    $con1 = [];
                    $con2 = [];
                    foreach ($result as $k => $v) {

                        $tops = $v['is_cluster'] ? $tops_cluster : $tops_chat;

                        if ($v['is_cluster']) {
                            $tops = $tops_cluster;
                            $tops_field = 'cluster_id';
                        } else {
                            $tops = $tops_chat;
                            $tops_field = 'userid';
                        }

                        if (in_array($v[$tops_field], $tops)) {
                            $v['top'] = 1;
                            $v['sort'] = array_search($v[$tops_field], $tops);
                            $con1[] = $v;
                        } else {
                            $con2[] = $v;
                        }
                    }

                    if ($con1) {
                        $tmp = array_column($con1, 'sort');
                        array_multisort($tmp, SORT_DESC, $con1);
                    }

                    $result = array_merge($con1, $con2);
                }
            }

            //array_multisort(array_column($result, 'addtime'), SORT_DESC, $result);

            if ($userid != $kefu) {
                $kefus = [];
                $contain1 = [];
                $contain2 = [];
                foreach ($result as $key => $item) {
                    if ($item['kefu']) {
                        $item['city'] = '';
                        $kefus[] = $item;
                    } else if (!$item['is_cluster'] && $item['touserid'] == $kefu) {
                        $contain1[] = $item;
                    } else {
                        $contain2[] = $item;
                    }
                }

                $result = array_merge($kefus, $contain1, $contain2);
            }

            foreach ($result as $key => $item) {
                /*$intimate = M('user_intimate')->where(['couple_a|couple_b' => $item['touserid'] . ',' . $userid, 'intimate' => ['gt', 0]])->getField('intimate');

                $result[$key]['intimate'] = $intimate ?: 0;*/

                $result[$key]['intimate'] = 0;
            }

            $data = json_encode(['code' => 200, 'data' => $result]);
        } else {
            $data = json_encode(['code' => 200, 'data' => []]);
        }

        exit($data);
    }

    // 发送信息
    public function addTalk($userid, $touserid, $type=0, $content='', $second=0, $data='', $timing=0, $greet=0, $system_greet=0, $login_greet=0, $single=0, $fate=0, $notice=0)
    {
        if ($type != 3) {
            $isWarnWord = 0;

            $pushNewMsgs = [];

            $content = strip_tags($content);
            $is_burn = I('is_burn') ?: 0;
            $config = M('config_system')->where(['category' => ['in', ['kefu', 'chat', 'greet', 'speaker', 'defend']]])->getField('title, content');
            $kefu = intval($config['id']);

            if($type == 0 && $kefu != $touserid && $kefu != $userid){
                if(ishasPhoneNumber($content)){
                    exit(json_encode(['code' => 400, 'msg' => '禁止发送手机号']));
                }
                // if($content[0] == '[' && substr($content, -1) == ']'){

                // }else{
                //     $sendNum = M('privatechat')->where(['userid'=>$userid, 'content'=>$content])->count();
                //     if($sendNum >= 5){
                //         exit(json_encode(['code' => 400, 'msg' => '禁止重复刷屏']));
                //     }
                // }
            }
            $blacklist = M('blacklist')->where(['user_id' => (int)$touserid, 'to_user' => (int)$userid])->find();
            if ($blacklist) {
                exit(json_encode(['code' => 400, 'msg' => '你已进入对方黑名单，无法发送消息']));
            }

            $userInfo = M('user')->master(true)->where(['id' => $userid])->find();
            $touserInfo = M('user')->master(true)->where(['id' => $touserid])->find();

            if (!$userInfo || !$touserInfo || $userInfo['delete_time'] || $touserInfo['delete_time']) {
                exit(json_encode(['code' => 400, 'msg' => '账号已注销']));
            }

            if ($userInfo['is_banned'] && strtotime($userInfo['banned_end_time']) > time()) {
                exit(json_encode(['code' => 400, 'msg' => '当前账号已被冻结']));
            }

            // if (!$userInfo['sandbox'] && $touserInfo['sandbox']) {
            //     exit(json_encode(['code' => 400, 'msg' => '无法给对方发送消息']));
            // }

            $delChat = M('del_chat')->Query("select * from del_chat where (uid=$userid and to_uid=$touserid) or (uid=$touserid and to_uid=$userid)");
            if ($delChat) {
                $del_ids = [$delChat[0]['id']];
                if (isset($delChat[1])) {
                    $del_ids[] = $delChat[1]['id'];
                }
                M('del_chat')->where(['id' => ['in', $del_ids]])->delete();
            }


            if ($kefu != $userid && $kefu != $touserid) {
                //if ($touserInfo['sex'] == '男' && $userInfo['sex'] == '女') {
                $touserConfig = ['chat_price' => 0];
                //} else {
                $touserConfig = M('config_personal')->where(['user_id' => $touserid])->find();

                if (!$touserConfig) {
                    $touserConfig = ['chat_price' => $config['chat_price']];
                } else {
                    $touserConfig = $config['chat_price_switch'] > 0 ? ['chat_price' => $config['chat_price']] : $touserConfig;
                }
                //}
            }


            $free = 0;

            $status = 0;  // 好友关系或守护关系
            $money = 0;
            if (!in_array($kefu, [$userid, $touserid]) || !$greet) {
                if (!in_array($type, [9, 10])) {
                    if ($touserConfig['chat_price'] + 0) {
                        /*$attention1 = M('attention')->where(['user_id' => $userid, 'to_user' => $touserid])->find();
                        $attention2 = M('attention')->where(['user_id' => $touserid, 'to_user' => $userid])->find();

                        if (!$attention1 || !$attention2) {*/
                        /*$defend = M('user_defend')->where(['user_id' => $touserid, 'to_user' => $userid, 'angel' => 1])->find();
                        if (!$defend) {*/
                        $status = 1;
                        //}
                        //}
                    }
                }
            }

            $chat_free = 0;
            if ($userid < $touserid) {
                $couple_a = $userid . ',' . $touserid;
            } else {
                $couple_a = $touserid . ',' . $userid;
            }

            //  其中一方属于系统推送过来的，只有男方是需要付费。否则，谁先发起对话，双方费用需都承担
            if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男') {
                if($userInfo['yqm'] != $touserInfo['yqr'] && ($fate==0 && $timing==0 && $greet==0)){

                    $selfpush = M('chat_lists')->where(['user_id'=>$userid, 'another_id'=>$touserid])->find();
                    $selfpull = M('chat_lists')->where(['another_id'=>$userid, 'user_id'=>$touserid])->find();


                    $otherlimit = !in_array($type, [1,11]) && !is_emoji($content);

                    // if($userInfo['realname_auth'] != 2 && $userInfo['yqm'] != $touserInfo['yqr'] && $kefu != $touserid && $kefu != $userid){
                        // $isHasChatWin = M()->Query("(select id from chat_lists where user_id=$touserid and another_id=$userid) union (select id from chat_lists where user_id=$userid and another_id=$touserid)");
                        if(!$selfpush && !$selfpull && $otherlimit){
                            // exit(json_encode(['code' => 400, 'msg' => '未实名认证不能主动向男用户发信息']));
                            exit(json_encode(['code' => 401, 'msg' => '不能主动向男用户发信息']));
                        }
                    // }

                    if($kefu != $touserid && $kefu != $userid && $otherlimit){
                        if(($selfpush && $selfpush['user_first'] == 1) || ($selfpull && $selfpull['another_first'] == 1)){
                            exit(json_encode(['code' => 400, 'msg' => '等待对方回复后才可继续聊天']));
                        }
                        // 亲密度
                        if($type == 0){
                            $intimate = M('user_intimate')->where(['couple_a' => $couple_a])->getField('intimate');
                            if(!$intimate || $intimate < 2){
                                if(is_hasNumber($content) || is_hasCnNumber($content)){
                                    exit(json_encode(['code' => 400, 'msg' => '亲密度达到2才能发数字']));
                                }
                            }
                        }
                    }
                }

                //$greetRecords = M()->Query("select id from greet_records where (user_id=$touserid and to_user=$userid) or (user_id=$userid and to_user=$touserid)");
                $greetRecords = false;

                if ($greetRecords) {
                    $status = 0;
                    $recharge_user = $touserInfo;
                } else {
                    $recharge_user = $userInfo;
                }
                $recharge_user = $touserInfo;
                $chat_free = 1;
            } else {
                $recharge_user = $userInfo;
            }

            switch ($type) {
                case 0:
                    if ($content == '') exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                    if (!$timing) {
                        // 敏感词检测
                        $contain = M('filter_word')->cache(true)->where(['state' => 1])->getField('name', true);
                        foreach ($contain as $k => $v) {
                            if (stripos($content, $v) !== false) {
                                exit(json_encode(['code' => 400, 'msg' => '消息含有敏感词"' . $v . '",请重新编辑发送']));
                            }
                        }

                        $extraMoney = 0;

                        if (!$chat_free && $kefu != $userid && $kefu != $touserid) { // 非客服咨询
                            /*if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $touserInfo['is_identity_authentication'] == 2) {
                                $chatRecord = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $userid, 'touserid' => $touserid])->find();
                                if (!$chatRecord) {
                                    $chatRecord = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $touserid, 'touserid' => $userid])->order('id desc')->find();
                                    if ($chatRecord) {
                                        $extraMoney = 1;
                                    }
                                }
                            }*/
                        } else {
                            $chat_free = 1;
                        }

                        if (!$chat_free) {
                            if ($status) {
                                $money = $touserConfig['chat_price'];

                                if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                    $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->cache(3600)->find();

                                    if ($gradeNoble) {
                                        $privilege = explode(',', $gradeNoble['privilege']);

                                        if (in_array(10, $privilege)) {
                                            $privilegeValue = explode(',', $gradeNoble['value']);

                                            if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                                $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                                $privilegeValue[0] = intval($privilegeValue[0]);

                                                if ($privilegeValue[0] > $userCount) {
                                                    M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                    //$touserConfig['chat_price'] = 0;

                                                    $free = 1;
                                                }
                                            }
                                        }
                                    }
                                }

                                if (!$free) {
                                    if ($recharge_user['free_chat']) {
                                        /*$chatCount = M('chat_records')->where(['types' => $type, 'user_id' => $userid])->count();

                                        if ($chatCount >= $config['chat_count']) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            M('chat_records')->add(['types' => $type, 'user_id' => $userid, 'to_user' => $touserid, 'create_time' => time()]);

                                            $money = 0;
                                        }*/

                                        M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                        $free = 1;
                                    } else {
                                        $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100) ? 0.1 : 0;
                                        if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                            if ($recharge_user['id'] == $userid) {
                                                exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                            } else {
                                                exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                            }
                                        }
                                    }
                                }
                            }

                            $money = $free ? 0 : $money;

                            if ($recharge_user['id'] == $userid) {
                                if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                } else {
                                    $chat_score = $money;
                                }

                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                            } else {
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                            }

                            /*if ($recharge_user['id'] == $userid) {
                                if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                } else {
                                    $chat_score = $money;
                                }
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                            } else {
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                            }*/

                            /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                                if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                } else {
                                    $chat_score = $money;
                                }
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => ($chat_score + $extraMoney) * 1];
                            } else {
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                            }*/
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'finish' => 1, 'single' => $single];
                        }


                        
                        // 添加聊天
                        // $id = M('privatechat')->add($contain);
                        // $contain['id'] = $id;
                        $pushNewMsgs[] = $contain;
                        
                        // 更新会话列表
                        D('ChatLists')->updateLists($userid, $touserid, $single, 0, $content, 0, $userInfo['sex']);


                        // 男性 客服自动回复
                        if ($userInfo['sex'] == '男' && $kefu == $touserid) {
                            $auto_customer_service = 0;

                            $customer_service_chat = M('customer_service_chat')->where(['user_id' => $userid])->find();
                            if ($customer_service_chat) {
                                if (($customer_service_chat['create_time'] + 3600) < time()) {
                                    $auto_customer_service = 1;
                                    M('customer_service_chat')->where(['id' => $customer_service_chat['id']])->setField('create_time', time());
                                }
                            } else {
                                $auto_customer_service = 1;
                                M('customer_service_chat')->add(['user_id' => $userid, 'create_time' => time()]);
                            }

                            if ($auto_customer_service) {
                                $auto_content = "由于用户群体比较大，人工客服只能处理身份审核以及突发事件，如需举报，投诉可去用户资料页去投诉用户，如需联系平台，可以去留言。感谢你的支持";
                                $contain = ['single' => 1, 'userid' => $touserid, 'touserid' => $userid, 'content' => $auto_content, 'finish' => 1];
                                // $id = M('privatechat')->add($contain);

                                // $contain['id'] = $id;
                                $pushNewMsgs[] = $contain;

                                // 更新会话列表
                                D('ChatLists')->updateLists($touserid, $userid, 1, 0, $auto_content);
                            }
                        }

                        // 预警词记录
                        if ($kefu != $userid) {
                            $warnWord = M('chat_warn_word')->where(['is_hidden' => 0])->cache(true)->getField('id, title');
                            foreach ($warnWord as $k => $v) {
                                if (stripos($content, $v) !== false) {
                                    M('chat_warn')->add(['user_id' => $userid, 'word_id' => $k, 'chat_id' => $id, 'create_time' => time()]);
                                    break;
                                }
                            }
                        }

                        // 提醒词记录
                        if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男' && $kefu != $userid && $kefu != $touserid) {
                            $warnWord = M('chat_tip_word')->where(['is_hidden' => 0])->cache(true)->getField('id, title, content');
                            foreach ($warnWord as $k => $v) {
                                if (stripos($content, $v['title']) !== false) {
                                    $contain = ['type' => -1, 'single' => 1, 'userid' => $userid, 'touserid' => $touserid, 'content' => $v['content'], 'finish' => 1];
                                    // $id = M('privatechat')->add($contain);

                                    // $contain['id'] = $id;
                                    $pushNewMsgs[] = $contain;

                                    $isWarnWord = 1;

                                    //$this->getNewMsg(json_encode(['userid' => $userid, 'touserid' => $touserid, 'type' => -1]));
                                    break;
                                }
                            }
                        }

                        if ($extraMoney) {
                            $rewardContent = '🎉🎉 恭喜，你的魅力吸引了小哥哥<br>👄 24小时内回复消息还可额外获得金币<br><br>上传更多照片能获得更多搭讪和积分哦~';
                            $contain_1 = ["userid" => $userid, "touserid" => $touserid, "type" => -1, 'single' => 1, "content" => $rewardContent, 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];
                            // $id = M('privatechat')->add($contain_1);

                            // $contain_1['id'] = $id;
                            $pushNewMsgs[] = $contain_1;
                        }
                    } else {
                        $location = I('location');  // 带有跳转链接

                        if ($location) {
                            $datas = I('data');
                            $datas = htmlspecialchars_decode($datas);
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'location' => $location, 'data' => $datas, 'finish' => 1];
                            // $id = M('privatechat')->add($contain);

                            // $contain['id'] = $id;
                            $pushNewMsgs[] = $contain;

                            // 更新会话列表
                            D('ChatLists')->updateLists($userid, $touserid, 0, 0, $content);
                        } else {
                            $speed = intval(I('speed'));  // 速配
                            $match = intval(I('match'));  // 夫妻相
                            //$fate = intval(I('fate'));  // 今日缘分

                            if ($speed) {
                                $types = $userInfo['sex'] == '男' ? 2 : 1;

                                $content_default = M('privatechat_default')->where(['types' => $types, 'channel' => 2, 'user_id' => ['in', [0, $touserid]]])->order('rand()')->getField('content');

                                if (!$content_default) {
                                    $content_default = M('privatechat_zhaohu')->where(['types' => $types, 'is_hidden' => 0])->order('rand()')->getField('content');
                                }
                                $speedContent = '❤ 同城速配成功，快把握住缘分吧~';
                                $contain_1 = ["userid" => $userid, "touserid" => $touserid, "type" => 0, 'single' => 1, "content" => $content];
                                $contain_2 = ["userid" => $touserid, "touserid" => $userid, "type" => 0, 'single' => 1, "content" => $content_default];
                                $contain_3 = ["userid" => $touserid, "touserid" => $userid, "type" => -1, 'single' => 1, "content" => $speedContent, 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];

                                // $id = M('privatechat')->add($contain_1);
                                // $contain_1['id'] = $id;
                                $pushNewMsgs[] = $contain_1;
                                // $id = M('privatechat')->add($contain_2);
                                // $contain_2['id'] = $id;
                                $pushNewMsgs[] = $contain_2;
                                //M('privatechat')->add($contain_3);

                                // 更新会话列表
                                D('ChatLists')->updateLists($userid, $touserid, 1, 0, $content);
                                D('ChatLists')->updateLists($touserid, $userid, 1, 0, $content_default);

                            } else if ($match) {
                                $matchContent = '👫 经大数据测算，你和对方具有夫妻相<br>👄 赶快向Ta打个招呼，把握缘分哦~';
                                $contain_1 = ["userid" => $touserid, "touserid" => $userid, "type" => -1, 'single' => 1, "content" => $matchContent, 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];
                                $contain_2 = ["userid" => $userid, "touserid" => $touserid, "type" => 0, "content" => $content, 'finish' => 1];

                                //M('privatechat')->add($contain_1);
                                // $id = M('privatechat')->add($contain_2);
                                // $contain_2['id'] = $id;
                                $pushNewMsgs[] = $contain_2;

                                // 更新会话列表
                                D('ChatLists')->updateLists($userid, $touserid, 0, 0, $content);
                            } else if ($fate) {
                                $contain = ["userid" => $userid, "touserid" => $touserid, "content" => $content, 'finish' => 1, 'is_fate' => 1];

                                // $id = M('privatechat')->add($contain);
                                // $contain['id'] = $id;
                                $pushNewMsgs[] = $contain;
                                // 更新会话列表
                                D('ChatLists')->updateLists($userid, $touserid, 0, 0, $content, 1);
                            } else if ($login_greet) {
                                $contain = ["userid" => $userid, "touserid" => $touserid, 'single' => 1, "content" => $content, 'finish' => 1];

                                // $id = M('privatechat')->add($contain);
                                // $contain['id'] = $id;
                                $pushNewMsgs[] = $contain;
                            } else if ($notice) {
                                $contain = ["userid" => $userid, "touserid" => $touserid, 'single' => $single, "content" => $content, 'finish' => 1];

                                // $id = M('privatechat')->add($contain);
                                // $contain['id'] = $id;
                                $pushNewMsgs[] = $contain;
                                // 更新会话列表
                                D('ChatLists')->updateLists($userid, $touserid, $single, 0, $content);
                            } else {
                                if ($userInfo['sex'] == '男') {
                                    $content = '❤ ← 丘比特 → 发现你俩今天很有缘，为你们牵线成功~';
                                    $greetContent = '❤ ← 丘比特 → 牵线成功，给对方发消息可领取红包奖励';
                                    $contain_1 = ["userid" => $userid, "touserid" => $touserid, "type" => 0, 'single' => 1, "content" => $content, 'data' => json_encode(['prefix' => '丘比特'], JSON_UNESCAPED_UNICODE)];
                                    $contain_2 = ["userid" => $userid, "touserid" => $touserid, "type" => -1, 'single' => 1, "content" => $greetContent, 'data' => json_encode(['prefix' => '丘比特'], JSON_UNESCAPED_UNICODE), 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];
                                } else {
                                    $greetContent = '❤ ← 丘比特 → 发现你俩今天很有缘~ <br>👄 赶紧聊聊吧，别错过缘分~';
                                    $contain_1 = ["userid" => $userid, "touserid" => $touserid, "type" => -1, 'single' => 1, "content" => $greetContent, 'data' => json_encode(['prefix' => '丘比特'], JSON_UNESCAPED_UNICODE), 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];
                                    $contain_2 = ["userid" => $userid, "touserid" => $touserid, "type" => 0, 'single' => 1, "content" => $content, 'data' => json_encode(['prefix' => '丘比特'], JSON_UNESCAPED_UNICODE), 'finish' => 1];
                                }

                                // $id = M('privatechat')->add($contain_1);
                                // $contain_1['id'] = $id;
                                $pushNewMsgs[] = $contain_1;
                                // $id = M('privatechat')->add($contain_2);
                                // $contain_2['id'] = $id;
                                $pushNewMsgs[] = $contain_2;
                            }
                        }
                    }

                    // if ($userid != $kefu && !$greet && !$notice) {
                        // 日常任务
                        /*$task = M('task')->where(['name' => 'word_chat'])->find();
                        if (($task['reward'] + 0) && ($task['max'] + 0)) {
                            $start = strtotime(date('Ymd'));
                            //$cost = M('volley_desc')->where(['user_id' => $userid, 'content' => '[完成任务] ' . $task['title'], 'time' => ['egt', $start]])->sum('price');

                            $cost = M('task_daily')->where(['user_id' => $userid, 'name' => $task['name'], 'create_time' => ['egt', $start]])->sum('reward');

                            if (($cost + $task['reward']) <= $task['max']) {
                                D('Task')->updateTaskDaily($userid, $task['name'], $task['reward']);

                                M('user_task')->add(['task' => $task['name'], 'user_id' => $userid, 'create_time' => time()]);

                                M('volley_desc')->add(['user_id' => $userid, 'content' => '[完成任务] ' . $task['title'], 'price' => $task['reward'], 'types' => 1, 'time' => time()]);

                                M('user')->where(['id' => $userid])->setInc('volley', $task['reward']);
                            }
                        }*/

                        // 任务
                    //     D('Task')->finish('word_chat', $userid);
                    // }
                    $msg = $content;
                    break;
                case 1:
                    if (!$content) exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                    if ($kefu == $userid || $kefu == $touserid) {
                        $chat_free = 1;
                    }

                    if (!$chat_free) {
                        if ($status) {
                            $money = $touserConfig['chat_price'];

                            if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                if ($gradeNoble) {
                                    $privilege = explode(',', $gradeNoble['privilege']);

                                    if (in_array(10, $privilege)) {
                                        $privilegeValue = explode(',', $gradeNoble['value']);

                                        if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                            $userCount = M('grade_noble_use')->where(['types' => 2, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                            $privilegeValue[0] = intval($privilegeValue[0]);
                                            if ($privilegeValue[0] > $userCount) {
                                                M('grade_noble_use')->add(['types' => 2, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                //$touserConfig['chat_price'] = 0;

                                                $free = 1;
                                            }
                                        }
                                    }
                                }
                            }

                            if (!$free) {
                                if ($recharge_user['free_chat']) {
                                    /*$chatCount = M('chat_records')->where(['types' => $type, 'user_id' => $userid])->count();

                                    if ($chatCount >= $config['chat_count']) {
                                        exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                    } else {
                                        M('chat_records')->add(['types' => $type, 'user_id' => $userid, 'to_user' => $touserid, 'create_time' => time()]);

                                        $money = 0;
                                    }*/

                                    M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');
                                } else {
                                    $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100) ? 0.1 : 0;
                                    if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                        if ($recharge_user['id'] == $userid) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                        }
                                    }
                                }
                            }
                        }

                        $money = $free ? 0 : $money;

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                        }

                        /*if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                        }*/

                        /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'is_burn' => $is_burn, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'is_burn' => $is_burn, 'money' => $money, 'score' => 0];
                        }*/
                    } else {
                        $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'is_burn' => $is_burn, 'finish' => 1];
                    }

                    // 添加聊天
                    // $id = M('privatechat')->add($contain);

                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    $msg = '[图片]';

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid, $touserid, 0, $type);

                    break;
                case 2:
                    if (!$content) exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                    if ($kefu == $userid || $kefu == $touserid) {
                        $chat_free = 1;
                    }

                    if (!$chat_free) {
                        if ($status) {
                            $money = $touserConfig['chat_price'];

                            $response = D('Privatechat')->checkFree($free, $money, $recharge_user, $userid);

                            if ($response['code'] != 200) {
                                exit(json_encode($response));
                            } else {
                                $free = $response['data']['free'];
                            }
                        }

                        $money = $free ? 0 : $money;

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'score' => 0];
                        }

                        /*if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                        }*/

                        /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'score' => 0];
                        }*/

                    } else {
                        $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "second" => $second, 'finish' => 1];
                    }

                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    $msg = '[语音]';

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid, $touserid, 0, $type);

                    break;
                case 3:
                    if (!$content) exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                    if ($kefu != $userid && $kefu != $touserid) { // 非客服咨询
                        // 被动聊天不扣费
                        /*$chatFreeUser = M('chat_free')->where(['user_id' => $userInfo['id'], 'to_user' => $touserInfo['id']])->find();

                        if ($chatFreeUser) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') {
                                $greetRecords = M('greet_records')->where(['user_id' => $userInfo['id'], 'to_user' => $touserInfo['id']])->find();

                                if (!$greetRecords) {
                                    $chat_free = 1;
                                }
                            } else if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男') {
                                $greetRecords = M('greet_records')->where(['user_id' => $touserInfo['id'], 'to_user' => $userInfo['id']])->find();

                                if (!$greetRecords) {
                                    $chat_free = 1;
                                }
                            } else {
                                $chat_free = 1;
                            }
                        } else {
                            $chatFreeToUser = M('chat_free')->where(['user_id' => $touserInfo['id'], 'to_user' => $userInfo['id']])->find();

                            if (!$chatFreeToUser) {
                                $record = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $touserInfo['id'], 'touserid' => $userInfo['id']])->find();

                                if (!$record) {
                                    M('chat_free')->add(['user_id' => $touserInfo['id'], 'to_user' => $userInfo['id'], 'create_time' => time()]);
                                }
                            }
                        }*/
                    } else {
                        $chat_free = 1;
                    }

                    if (!$chat_free) {
                        if ($status) {
                            $money = $touserConfig['chat_price'];

                            $response = D('Privatechat')->checkFree($free, $money, $recharge_user, $userid);

                            if ($response['code'] != 200) {
                                exit(json_encode($response));
                            } else {
                                $free = $response['data']['free'];
                            }
                        }

                        $money = $free ? 0 : $money;

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, "data" => json_encode(['cover' => I('cover')]), 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, "data" => json_encode(['cover' => I('cover')]), 'score' => 0];
                        }

                        /*if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                        }*/

                        /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "data" => json_encode(['cover' => I('cover')]), 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "data" => json_encode(['cover' => I('cover')]), 'money' => $money, 'score' => 0];
                        }*/
                    } else {
                        $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "data" => json_encode(['cover' => I('cover')]), 'finish' => 1];
                    }

                    // 添加聊天
                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    $msg = '[视频]';

                    // 更新会话列表
                    //D('ChatLists')->updateLists($userid, $touserid, 0, 3);

                    break;
                case 6:
                    if (!$content) exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                    $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $money * 1];

                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    $msg = '[位置]';
                    break;
                case 8:
                    $id = I('id');
                    $num = I('num');
                    $num = intval($num);

                    if ($num <= 0) exit(json_encode(['code' => 400, 'msg' => '数量有误']));

                    $gift = M('gift')->find($id);
                    if (!$gift) exit(json_encode(['code' => 400, 'msg' => '礼物类型不存在']));

                    if ($gift['types'] == 2) {
                        if (!$userInfo['noble_grade'] || $userInfo['noble_time'] < time()) {
                            exit(json_encode(['code' => 400, 'msg' => '需先开通贵族']));
                        }

                        $gradeNoble = M()->Query("SELECT * from grade_noble where FIND_IN_SET(6, privilege) order by grade asc limit 1");

                        if (!$gradeNoble) {
                            exit(json_encode(['code' => 400, 'msg' => '无权限']));
                        }

                        if ($userInfo['noble_grade'] < $gradeNoble[0]['grade']) {
                            exit(json_encode(['code' => 400, 'msg' => '需先开通' . $gradeNoble[0]['name'] . '贵族或以上等级的贵族']));
                        }
                    }

                    $money = $gift['price'] * $num;

                    $time = time();
                    $number = date('YmdHis') . mt_rand(1000, 9999);

                    //$volley = M('user')->where(['id' => $userid])->getField('volley');
                    $volley = $userInfo['volley'];
                    if ($userInfo['sex'] == '男') {
                        if ($volley < $money * (1 + 0.03)) {
                            if ($volley < $money) exit(json_encode(['code' => 400, 'msg' => '余额不足']));
                        }

                        //if ($volley < $money * (1 + 0.03)) {exit(json_encode(['code' => 400, 'msg' => '余额不足']));
                        // 额外金额注释
                        //if ($volley < $money) exit(json_encode(['code' => 400, 'msg' => '余额不足']));
                    } else {
                        if ($volley < $money) exit(json_encode(['code' => 400, 'msg' => '余额不足']));
                    }

                    $contain = [
                        "userid" => $userid,
                        "touserid" => $touserid,
                        "type" => $type,
                        "content" => '[礼物]',
                        'money' => $money,
                        'score' => $money * 1,
                        'finish' => 1,
                        "data" => json_encode(['money' => $money, 'id' => $id, 'cover' => $gift['cover'], 'num' => $num, 'name' => $gift['name']]),
                    ];

                    // 添加聊天
                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;


                    /*M('gift_record')->add([
                        'num' => $num,
                        'gift_id' => $gift['id'],
                        'user_id' => $userid,
                        'to_user' => $touserid,
                    ]);*/

                    if ($money > 0) {
                        // 扣除余额
                        D('VolleyDesc')->index($userid, $money * 1, '给' . $touserInfo['name'] . '(' . $touserInfo['id'] . ')赠送礼物：' . $gift['name'] . ' X ' . $num);

                        // 创建订单
                        M('order_common')->add([
                            'number' => $number,
                            'user_id' => $userid,
                            'money' => $money,
                            'status' => 1,
                            'types' => 4,
                            'data' => json_encode(['id' => $id, 'touserid' => $touserid, 'num' => $num]),
                            'create_time' => $time,
                            'update_time' => $time,
                        ]);

                        // 电视墙
                        /*if ($userInfo['speaker'] != 3) {
                            if ($config['speaker_min'] <= $money) {

                                $background = '';
                                if ($config['speaker_special'] <= $money) {
                                    $speakerBackground = M('speaker_background')->where(['id' => ['gt', 0]])->order('rand()')->find();

                                    if ($speakerBackground) {
                                        $background = $speakerBackground['image'];
                                    }
                                }

                                $speakerBlock = M('speaker_block')->where(['min' => ['elt', $money]])->order('min desc')->find();
                                $block = $speakerBlock ? $speakerBlock['second'] : $config['expire'];

                                if ($userInfo['speaker'] == 1) {
                                    $user_id = $userid;
                                    $user_name = $userInfo['name'];
                                } else {
                                    $user_id = '';
                                    $user_name = '神秘人';
                                }

                                if ($touserInfo['speaker'] == 1) {
                                    $another_id = $touserid;
                                    $another_name = $touserInfo['name'];
                                } else {
                                    $another_id = '';
                                    $another_name = '神秘人';
                                }

                                M('speaker')->add([
                                    'types' => 2,
                                    'user_id' => $userid,
                                    'to_user' => $touserid,
                                    'content' => '',
                                    'data' => json_encode([
                                        'gift_id' => $id,
                                        'gift_name' => $gift['name'],
                                        'gift_cover' => $gift['cover'],
                                        'gift_price' => $gift['price'],
                                        'gift_num' => $num,
                                        'user_id' => $user_id,
                                        'user_name' => $user_name,
                                        'another_id' => $another_id,
                                        'another_name' => $another_name,
                                        'background' => $background,
                                        'block' => $block,
                                        'time' => date('H:i')
                                    ], JSON_UNESCAPED_UNICODE),
                                    'create_time' => time(),
                                ]);
                            }
                        }

                        $url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . str_replace('home/' . $_SERVER['PATH_INFO'], '', str_replace('apis', '', $_SERVER['SCRIPT_NAME'])) . '/api/Speaker/lists';

                        $data = $this->getcurl($url, []);*/

                        if ($userid < $touserid) {
                            $field_count = 'count_a';
                            $couple_a = $userid . ',' . $touserid;
                            $couple_b = $touserid . ',' . $userid;
                        } else {
                            $field_count = 'count_b';
                            $couple_a = $touserid . ',' . $userid;
                            $couple_b = $userid . ',' . $touserid;
                        }

                        $intimate = M('user_intimate')->where(['couple_a' => $couple_a])->find();
                        if ($intimate) {
                            M('user_intimate')->where(['id' => $intimate['id']])->save([
                                $field_count => $intimate[$field_count] + $money,
                                'intimate' => $intimate['intimate'] + $money * 1,
                                'update_time' => time()
                            ]);
                        } else {
                            M('user_intimate')->add([
                                'couple_a' => $couple_a,
                                'couple_b' => $couple_b,
                                $field_count => $money,
                                'intimate' => $money * 1,
                                'create_time' => time(),
                                'update_time' => time()
                            ]);
                        }

                        M('user')->where(['id' => $touserid])->setInc('charm_value', $money * 1);

                        // 榜单记录
                        /*$records_types = $touserInfo['sex'] == '女' ? '1,2,3,6' : '1,3,4,6';
                        D('RankingRecords')->index($records_types, $userid, $touserid, $money);*/


                        // 分成
                        $fencheng_content = '收获' . $userInfo['name'] . '(' . $userInfo['id'] . ')赠送的礼物：' . $gift['name'] . 'X' . $num;

                        D('User')->fencheng($touserid, $userid, $money * 1, 'gift', $fencheng_content);

                        /*$intimate = M('user_intimate')->where(['couple_a' => $couple_a])->find();

                        $result = M('user_defend')->where(['user_id' => $userid, 'to_user' => $touserid])->find();

                        $types = $touserInfo['sex'] == '女' ? 2 : 1;
                        $gradeCharm = M('grade_charm')->where(['types' => $types, 'min' => ['elt', $touserInfo['charm_value']]])->order('grade desc')->getField('grade');

                        if ($touserInfo['sex'] == '女') {
                            $gift_money = $gradeCharm * $config['female_times'];
                            if ($gift_money < $config['female_min']) {
                                $gift_money = $config['female_min'];
                            }
                        } else {
                            $gift_money = $gradeCharm * $config['male_times'];
                            if ($gift_money < $config['male_min']) {
                                $gift_money = $config['male_min'];
                            }
                        }

                        if (!$touserInfo['angel']) {

                            $hadMoney = $userid < $touserid ? $intimate['count_a'] : $intimate['count_b'];

                            $mustMoney = $gift_money - ($hadMoney - $money);

                            $isAngel = 0;
                            if ($mustMoney <= $money) {
                                $isAngel = 1;
                            } else {
                                $gradeDefend = M('grade_defend')->where(['min' => ['elt', $hadMoney]])->order('grade desc')->find();

                                if ($gradeDefend) {
                                    $isAngel = 1;
                                }
                            }

                            if ($isAngel) {
                                M('user')->where(['id' => $touserid])->setField('angel', $userid);
                                M('user_defend')->where(['user_id' => ['neq', $userid], 'to_user' => $touserid])->save(['angel' => 0, 'update_time' => time()]);

                                $isAngel = 1;
                                $update_time = time();

                                // 任务
                                D('Task')->finish('defend', $userid);
                            } else {
                                $isAngel = 0;
                                $update_time = $result ? $result['update_time'] : time();
                            }

                            $defend_money = $hadMoney;
                        } else {
                            $angel = M('user_defend')->where(['to_user' => $touserid, 'angel' => 1])->find();

                            if ($result) {
                                $defend_money_new = $result['money'] + $money;
                            } else {
                                $defend_money_new = $money;
                            }

                            if (($angel['money'] < $defend_money_new) && $angel['user_id'] != $userid && $gift_money <= $defend_money_new) {

                                M('user')->where(['id' => $touserid])->setField('angel', $userid);
                                M('user_defend')->where(['user_id' => ['neq', $userid], 'to_user' => $touserid])->save(['angel' => 0, 'update_time' => time()]);

                                $isAngel = 1;
                                $update_time = time();

                                // 任务
                                D('Task')->finish('defend', $userid);
                            } else {
                                $isAngel = 0;
                                $update_time = $angel['update_time'];
                            }

                            //$defend_money = $result['money'];
                            $defend_money = $defend_money_new;
                        }

                        if ($result) {
                            M('user_defend')->where(['id' => $result['id']])->save(['angel' => $isAngel, 'money' => $defend_money, 'update_time' => $update_time]);
                        } else {
                            M('user_defend')->add([
                                'user_id' => $userid,
                                'to_user' => $touserid,
                                'money' => $defend_money,
                                'angel' => $isAngel,
                                'create_time' => time(),
                                'update_time' => time(),
                            ]);
                        }*/
                    }

                    $msg = '[礼物]';

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid, $touserid, 0, 8);

                    break;
                case 11:
                    if (!$content) exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                    $content = intval($content);

                    $where = [
                        'id' => $content,
                        'is_hidden' => 0,
                    ];
                    $sticker = M('chat_sticker')->field('image')->where($where)->find();
                    if (!$sticker) {
                        exit(json_encode(['code' => 400, 'msg' => '表情不存在或已下线']));
                    } else {
                        $content = $sticker['image'];
                    }


                    $extraMoney = 0;

                    if (!$chat_free && $kefu != $userid && $kefu != $touserid) { // 非客服咨询
                    } else {
                        $chat_free = 1;
                    }

                    if (!$chat_free) {
                        if ($status) {
                            $money = $touserConfig['chat_price'];

                            if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                if ($gradeNoble) {
                                    $privilege = explode(',', $gradeNoble['privilege']);

                                    if (in_array(10, $privilege)) {
                                        $privilegeValue = explode(',', $gradeNoble['value']);

                                        if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                            $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                            $privilegeValue[0] = intval($privilegeValue[0]);

                                            if ($privilegeValue[0] > $userCount) {
                                                M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                //$touserConfig['chat_price'] = 0;

                                                $free = 1;
                                            }
                                        }
                                    }
                                }
                            }

                            if (!$free) {
                                if ($recharge_user['free_chat']) {

                                    M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                    $free = 1;
                                } else {
                                    $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100) ? 0.1 : 0;
                                    if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                        if ($recharge_user['id'] == $userid) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                        }
                                    }
                                }
                            }
                        }

                        $money = $free ? 0 : $money;

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                        }

                    } else {
                        $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'finish' => 1];
                    }
                    
                    // 添加聊天
                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;
                    
                    // 更新会话列表
                    D('ChatLists')->updateLists($userid, $touserid, $single, 11, $content, 0, $userInfo['sex']);

                    // if ($userid != $kefu && !$greet && !$notice) {
                        // 任务
                    //     D('Task')->finish('word_chat', $userid);
                    // }
                    $msg = '[表情]';
                    break;
                case 12:
                    if ($content == '') exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                        // 敏感词检测
                        $contain = M('filter_word')->cache(true)->where(['state' => 1])->getField('name', true);
                        foreach ($contain as $k => $v) {
                            if (stripos($content, $v) !== false) {
                                exit(json_encode(['code' => 400, 'msg' => '消息含有敏感词"' . $v . '",请重新编辑发送']));
                            }
                        }

                        $extraMoney = 0;

                        if (!$chat_free && $kefu != $userid && $kefu != $touserid) { // 非客服咨询
                            /*if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $touserInfo['is_identity_authentication'] == 2) {
                                $chatRecord = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $userid, 'touserid' => $touserid])->find();
                                if (!$chatRecord) {
                                    $chatRecord = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $touserid, 'touserid' => $userid])->order('id desc')->find();
                                    if ($chatRecord) {
                                        $extraMoney = 1;
                                    }
                                }
                            }*/
                        } else {
                            $chat_free = 1;
                        }

                        if (!$chat_free) {
                            if ($status) {
                                $money = $touserConfig['chat_price'];

                                if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                    $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                    if ($gradeNoble) {
                                        $privilege = explode(',', $gradeNoble['privilege']);

                                        if (in_array(10, $privilege)) {
                                            $privilegeValue = explode(',', $gradeNoble['value']);

                                            if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                                $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                                $privilegeValue[0] = intval($privilegeValue[0]);

                                                if ($privilegeValue[0] > $userCount) {
                                                    M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                    //$touserConfig['chat_price'] = 0;

                                                    $free = 1;
                                                }
                                            }
                                        }
                                    }
                                }

                                if (!$free) {
                                    if ($recharge_user['free_chat']) {
                                        /*$chatCount = M('chat_records')->where(['types' => $type, 'user_id' => $userid])->count();

                                        if ($chatCount >= $config['chat_count']) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            M('chat_records')->add(['types' => $type, 'user_id' => $userid, 'to_user' => $touserid, 'create_time' => time()]);

                                            $money = 0;
                                        }*/

                                        M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                        $free = 1;
                                    } else {
                                        $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100) ? 0.1 : 0;
                                        if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                            if ($recharge_user['id'] == $userid) {
                                                exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                            } else {
                                                exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                            }
                                        }
                                    }
                                }
                            }

                            $money = $free ? 0 : $money;

                            if ($recharge_user['id'] == $userid) {
                                if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                } else {
                                    $chat_score = $money;
                                }

                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                            } else {
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                            }

                            /*if ($recharge_user['id'] == $userid) {
                                if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                } else {
                                    $chat_score = $money;
                                }
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                            } else {
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                            }*/

                            /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                                if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                } else {
                                    $chat_score = $money;
                                }
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => ($chat_score + $extraMoney) * 1];
                            } else {
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                            }*/
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'finish' => 1, 'single' => $single];
                        }

                        if($data){
                            $contain['data'] = $data;
                        }else{
                            exit(json_encode(['code' => 400, 'msg' => '操作错误']));
                        }
                        
                        // 添加聊天
                        // $id = M('privatechat')->add($contain);
                        // $contain['id'] = $id;
                        $pushNewMsgs[] = $contain;
                        
                        // 更新会话列表
                        D('ChatLists')->updateLists($userid, $touserid, $single, 0, $content, 0, $userInfo['sex']);


                        // 男性 客服自动回复
                        if ($userInfo['sex'] == '男' && $kefu == $touserid) {
                            $auto_customer_service = 0;

                            $customer_service_chat = M('customer_service_chat')->where(['user_id' => $userid])->find();
                            if ($customer_service_chat) {
                                if (($customer_service_chat['create_time'] + 3600) < time()) {
                                    $auto_customer_service = 1;
                                    M('customer_service_chat')->where(['id' => $customer_service_chat['id']])->setField('create_time', time());
                                }
                            } else {
                                $auto_customer_service = 1;
                                M('customer_service_chat')->add(['user_id' => $userid, 'create_time' => time()]);
                            }

                            if ($auto_customer_service) {
                                $auto_content = "由于用户群体比较大，人工客服只能处理身份审核以及突发事件，如需举报，投诉可去用户资料页去投诉用户，如需联系平台，可以去留言。感谢你的支持";
                                $contain = ['single' => 1, 'userid' => $touserid, 'touserid' => $userid, 'content' => $auto_content, 'finish' => 1];
                                // $id = M('privatechat')->add($contain);
                                // $contain['id'] = $id;
                                $pushNewMsgs[] = $contain;

                                // 更新会话列表
                                D('ChatLists')->updateLists($touserid, $userid, 1, 0, $auto_content);
                            }
                        }

                        // 预警词记录
                        if ($kefu != $userid) {
                            $warnWord = M('chat_warn_word')->cache(true)->where(['is_hidden' => 0])->getField('id, title');
                            foreach ($warnWord as $k => $v) {
                                if (stripos($content, $v) !== false) {
                                    M('chat_warn')->add(['user_id' => $userid, 'word_id' => $k, 'chat_id' => $id, 'create_time' => time()]);
                                    break;
                                }
                            }
                        }

                        // 提醒词记录
                        if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男' && $kefu != $userid && $kefu != $touserid) {
                            $warnWord = M('chat_tip_word')->cache(true)->where(['is_hidden' => 0])->getField('id, title, content');
                            foreach ($warnWord as $k => $v) {
                                if (stripos($content, $v['title']) !== false) {
                                    $contain = ['type' => -1, 'single' => 1, 'userid' => $userid, 'touserid' => $touserid, 'content' => $v['content'], 'finish' => 1];
                                    // $id = M('privatechat')->add($contain);
                                    // $contain['id'] = $id;
                                    $pushNewMsgs[] = $contain;

                                    $isWarnWord = 1;

                                    //$this->getNewMsg(json_encode(['userid' => $userid, 'touserid' => $touserid, 'type' => -1]));
                                    break;
                                }
                            }
                        }


                    // if ($userid != $kefu && !$greet && !$notice) {
                    //     // 任务
                    //     D('Task')->finish('word_chat', $userid);
                    // }
                    $msg = $content;
                    break;
                default:
                    exit(json_encode(['code' => 400, 'msg' => '操作错误']));
            }
            M()->startTrans();
            if (!$system_greet) {
                if (!in_array($kefu, [$userid, $touserid]) || !$greet) {
                    if (!in_array($type, [8, 9, 10])) {
                        if (!$free && ($money + 0)) {
                            if ($recharge_user['id'] == $userid || !$chat_free) {
                                $recharge_msg = $recharge_user['id'] == $userid ? '给' . $touserInfo['name'] . '(' . $touserInfo['id'] . ')发消息扣金币' : $userInfo['name'] . '(' . $userInfo['id'] . ')发消息扣金币';
                                // 扣除余额
                                $IncOk = D('VolleyDesc')->index($recharge_user['id'], $money, $recharge_msg);
                            }else{
                                $IncOk = true;
                            }
                        }else{
                            $IncOk = true;
                        }
                    }else{
                        $IncOk = true;
                    }

                    if($recharge_user['id'] != $userid){


                        $scoreChat = M('privatechat')->master(true)->where(['userid' => $touserid, 'touserid' => $userid, 'score' => ['gt', 0], 'finish' => 0])->select();

                        $ids = array_column($scoreChat, 'id');

                        M('privatechat')->where(['id' => ['in', $ids]])->save(['finish' => 1]);
                        $scoreData = [];
                        $scoreUpdate = 0;

                        $content = '回复' . $touserInfo['name'] . '(' . $touserInfo['id'] . ')的消息获得积分';

                        foreach ($scoreChat as $item) {
                            if (!in_array($item['type'], [8, 9, 10])) {
                                $money = $item['score'];
                            } else {
                                $money = 0;
                            }

                            $scoreData[] = [
                                'uid' => $userid,
                                'touid' => $touserid,
                                'content' => $content,
                                'money' => $money,
                                'type' => 1,
                                'time' => time(),
                            ];

                            $scoreUpdate += $money;
                        }

                        if ($scoreUpdate) {

                            if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '女') {

                            } else {
                                // 榜单记录
                                //D('RankingRecords')->index(1, $userid, $touserid, $scoreUpdate * 10);

                                foreach ($scoreData as $value) {
                                    if($value['money']){
                                        // 分成
                                        D('User')->fencheng($userid, $touserid, $value['money'], 'chat', $content);
                                    }
                                }

                                //M('yaoqing_records')->addAll($scoreData);
                                //M('user')->where(['id' => $userid])->setInc('score', $scoreUpdate);
                                M('user')->where(['id' => $userid])->setInc('charm_value', $scoreUpdate);
                            }


                            // 亲密度
                            if ($userid < $touserid) {
                                $field_count = 'count_b';
                                $couple_a = $userid . ',' . $touserid;
                                $couple_b = $touserid . ',' . $userid;
                            } else {
                                $field_count = 'count_a';
                                $couple_a = $touserid . ',' . $userid;
                                $couple_b = $userid . ',' . $touserid;
                            }

                            $intimate = M('user_intimate')->master(true)->where(['couple_a' => $couple_a])->find();
                            if ($intimate) {
                                M('user_intimate')->where(['id' => $intimate['id']])->save([
                                    $field_count => $intimate[$field_count] + $scoreUpdate * 10,
                                    'intimate' => $intimate['intimate'] + $scoreUpdate,
                                    'update_time' => time()
                                ]);
                            } else {
                                M('user_intimate')->add([
                                    'couple_a' => $couple_a,
                                    'couple_b' => $couple_b,
                                    $field_count => $scoreUpdate * 10,
                                    'intimate' => $scoreUpdate,
                                    'create_time' => time(),
                                    'update_time' => time()
                                ]);
                            }
                            /*$intimate = M('user_intimate')->where(['couple_a' => $couple_a])->find();

                            $result = M('user_defend')->where(['user_id' => $touserid, 'to_user' => $userid])->find();

                            if (!$userInfo['angel']) {

                                $types = $userInfo['sex'] == '女' ? 2 : 1;
                                $gradeCharm = M('grade_charm')->where(['types' => $types, 'min' => ['elt', $userInfo['charm_value']]])->order('grade desc')->getField('grade');

                                //$gift_money = $userInfo['sex'] == '女' ? $gradeCharm * 100 : $gradeCharm * 20;

                                if ($userInfo['sex'] == '女') {
                                    $gift_money = $gradeCharm * $config['female_times'];
                                    if ($gift_money < $config['female_min']) {
                                        $gift_money = $config['female_min'];
                                    }
                                } else {
                                    $gift_money = $gradeCharm * $config['male_times'];
                                    if ($gift_money < $config['male_min']) {
                                        $gift_money = $config['male_min'];
                                    }
                                }

                                $hadMoney = $userid > $touserid ? $intimate['count_a'] : $intimate['count_b'];

                                $mustMoney = $gift_money - ($hadMoney - $money);

                                $isAngel = 0;
                                if ($mustMoney <= $money) {
                                    $isAngel = 1;
                                } else {
                                    $gradeDefend = M('grade_defend')->where(['min' => ['elt', $hadMoney]])->order('grade desc')->find();

                                    if ($gradeDefend) {
                                        $isAngel = 1;
                                    }
                                }

                                if ($isAngel) {
                                    M('user')->where(['id' => $userid])->setField('angel', $touserid);
                                    M('user_defend')->where(['user_id' => ['neq', $touserid], 'to_user' => $userid])->save(['angel' => 0, 'update_time' => $update_time]);

                                    $isAngel = 1;
                                    $update_time = time();
                                } else {
                                    $isAngel = 0;
                                    $update_time = $result ? $result['update_time'] : time();
                                }

                                $defend_money = $hadMoney;
                            } else {
                                $angel = M('user_defend')->where(['to_user' => $userid, 'angel' => 1])->find();

                                if (($angel['money'] < $result['money']) && $angel['user_id'] != $touserid) {

                                    M('user')->where(['id' => $userid])->setField('angel', $touserid);
                                    M('user_defend')->where(['user_id' => ['neq', $touserid], 'to_user' => $userid])->save(['angel' => 0, 'update_time' => $update_time]);

                                    $isAngel = 1;
                                    $update_time = time();
                                } else {
                                    $isAngel = 0;
                                    $update_time = $angel['update_time'];
                                }

                                $defend_money = $result['money'];
                            }

                            if ($result) {
                                M('user_defend')->where(['id' => $result['id']])->save(['angel' => $isAngel, 'money' => $defend_money, 'update_time' => $update_time]);
                            } else {
                                M('user_defend')->add([
                                    'user_id' => $touserid,
                                    'to_user' => $userid,
                                    'money' => $defend_money,
                                    'angel' => $isAngel,
                                    'create_time' => time(),
                                    'update_time' => time(),
                                ]);
                            }*/
                        }


                    }

                    //---------------------------

                    // 魅力值
                    if ($money + 0) {
                        M('user')->where(['id' => $userid])->setInc('tycoon', $money * 1);
                    }
                }else{
                    $IncOk = true;
                }
            }else{
                $IncOk = true;
            }
            foreach ($pushNewMsgs as $pmk => $pmv) {
                $pushNewMsgs[$pmk]['id'] = M('privatechat')->add($pmv);
            }

            if($IncOk){
                M()->startTrans();
            }else{
                M()->rollback();
                exit(json_encode(['code' => 400, 'msg' => '服务繁忙']));
            }

            // 清除聊天缓存
            S("getMsgList$userid&$touserid",null);
            S("getMsgList$touserid&$userid",null);



            if ($userid != $kefu && !$greet && !$notice && in_array($type, [0, 12])) {
                // 任务
                D('Task')->finish('word_chat', $userid);
            }

            if(!$system_greet) {

                foreach ($pushNewMsgs as $pmk => $pmv) {
                    $this->pushNewMsg($pmv);
                }
                // $this->getNewMsg(json_encode(['userid' => $userid, 'touserid' => $touserid]));
                $this->getOtherList(json_encode(['userid' => $touserid, 'count' => '', 'type' => '']));
                // 推送
                if(!$touserInfo['unpush']){
                    $datas = json_encode(['type' => 2, 'userid' => $userid, 'name' => $userInfo['name']], JSON_UNESCAPED_UNICODE);
                    D('Push')->send(2, $touserid, $userInfo['name'], $msg, $datas);
                }
            }

            $this->getOtherList(json_encode(['userid' => $userid, 'count' => '', 'type' => '']));

            if ($timing) {
                $this->getreadcount(json_encode(['user_id' => $touserid]));
            }

            if(I('return') && $pushNewMsgs[0]){
                if(!isset($intimate)){
                    $intimate = M('user_intimate')->where(['couple_a' => $couple_a])->getField('intimate');
                }
                $pushNewMsgs[0]['intimate'] = $intimate;
                exit(json_encode(['code'=>200,'data'=>$pushNewMsgs[0]]));
            }


        }
    }
    // 不走数据库推送新消息
    private function pushNewMsg($data)
    {
        $userid = $data['userid'];
        $touserid = $data['touserid'];
        $result = $data;

        if(!isset($result['type'])){ $result['type'] = 0; }
        if(!isset($result['status'])){ $result['status'] = "0"; }
        if(!isset($result['state'])){ $result['state'] = "0"; }
        if(!isset($result['second'])){ $result['second'] = "0"; }
        if(!isset($result['is_burn'])){ $result['is_burn'] = "0"; }
        if(!isset($result['k'])){ $result['k'] = "0"; }
        if(!isset($result['money'])){ $result['money'] = '0.00'; }
        if(!isset($result['score'])){ $result['score'] = '0.00'; }
        if(!isset($result['location'])){ $result['location'] = "0"; }
        if(!isset($result['isRead'])){ $result['isRead'] = "0"; }
        if(!isset($result['isCount'])){ $result['isCount'] = "0"; }
        if(!isset($result['sound_tip'])){ $result['sound_tip'] = "0"; }
        if(!isset($result['sms_tip'])){ $result['sms_tip'] = "0"; }
        if(!isset($result['is_public'])){ $result['is_public'] = "0"; }
        if(!isset($result['is_fate'])){ $result['is_fate'] = "0"; }
        if(!isset($result['order_id'])){ $result['order_id'] = "0"; }
        if(!isset($result['addtime'])){ $result['addtime'] = date('Y-m-d H:i:s'); }

        $data = ['new' => [], 'recall' => [], 'users' => ['userid' => $touserid, 'touserid' => $userid, 'intimate' => 0]];
    
        $users = M('user')->where(['id' => ['in', [$userid, $touserid]]])->cache(86400)->getField('id, name, head_100 head_portrait, sex');


        if ($result) {
            $result['self'] = $userid == $result['userid'] ? 1 : 0;

            $result['name'] = $users[$result['userid']]['name'];
            $result['head_portrait'] = $users[$result['userid']]['head_portrait'];

            $datas = json_decode($result['data'], true);

            if (isset($datas['image'])) {
                $datas['image'] = changeUrl($datas['image']);
            }

            if (in_array($result['type'], [9, 10])) {
                if (isset($datas['status']) && $datas['status']) {
                    if (isset($datas['start']) && isset($datas['end'])) {
                        $chat_time = $datas['end'] - $datas['start'];
                        $result['chat_time'] = changeTime($chat_time);
                    } else {
                        if ($datas['second']) {
                            $result['content'] .= changeTime($datas['second'] * 60);
                        } else {
                            $result['content'] .= '01:00';
                        }
                    }
                    if($result['type'] == 9){
                        D('UserActiveval')->inc($userid, 'chatforaudio');
                    }else{
                        D('UserActiveval')->inc($userid, 'chatforvideo');
                    }
                } else {
                    $result['content'] .= ' 未接通';
                }
            }else{
                D('UserActiveval')->inc($userid, 'chatformsg');
            }

            $result['data'] = $datas;

            $data['new'][] = $result;

            $couple_a = $userid < $touserid ? $userid . ',' . $touserid : $touserid . ',' . $userid;
            $intimate = M('user_intimate')->where(['couple_a' => $couple_a])->getField('intimate');

            $data['users']['intimate'] = $intimate ?: 0;
        }

        $contain = $data;
        foreach ($contain['new'] as $k => $v) {
            $v['self'] = $v['self'] ? 0 : 1;
            $contain['new'][$k] = $v;
        }

        if (!empty($data['new']) || !empty($data['recall'])) {
            if (isset($result[0]) && $result[0]['single']) {
                $data = [];
            }
            $message1 = json_encode(['code' => 200, 'v' => 1, 'action' => 'Home/Privatechat/getNewMsg', 'data' => $contain]);
            $message2 = json_encode(['code' => 200, 'v' => 1, 'action' => 'Home/Privatechat/getNewMsg', 'data' => $data]);
        } else {
            $message1 = $message2 = json_encode(['code' => 400, 'v' => 1, 'action' => 'Home/Privatechat/getNewMsg', 'data' => []]);
        }

        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, $message1);
        if($result['single']==0){
            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $userid, $message2);
        }
    }

    // 获取新消息
    public function getNewMsg($data)
    {
        $data = json_decode($data, true);

        $userid = $data['userid'];
        $touserid = $data['touserid'];

        $type = isset($data['type']) ? " = " . $data['type'] : " <> -1";

        $Model = M();

        $data = ['new' => [], 'recall' => [], 'users' => ['userid' => $touserid, 'touserid' => $userid, 'intimate' => 0]];
    
        $users = M('user')->where(['id' => ['in', [$userid, $touserid]]])->cache(86400)->getField('id, name, head_100 head_portrait, sex');

        /*$sql = <<<sql
            SELECT t.*, t1.head_100 as head_portrait, t1.name, t.addtime FROM privatechat t, user t1 
            WHERE t.userid = $userid  AND t.touserid = $touserid and t.status not in (-1,2) AND t.isRead = 0 AND (t.type $type AND t.state <> 1) AND t.userid = t1.id 
            ORDER BY t.id desc limit 0,1
sql;*/
    
        $sql = <<<sql
            SELECT t.* FROM privatechat t
            WHERE userid = $userid  AND touserid = $touserid and status not in (-1,2) AND isRead = 0 AND (type $type AND state <> 1)
            ORDER BY id desc limit 0,1
sql;
        $result = $Model->Query($sql);

        if ($result) {
            foreach ($result as $key => $item) {
                $result[$key]['self'] = $userid == $item['userid'] ? 1 : 0;
    
                $result[$key]['name'] = $users[$item['userid']]['name'];
                $result[$key]['head_portrait'] = $users[$item['userid']]['head_portrait'];

                $datas = json_decode($item['data'], true);

                if (isset($datas['image'])) {
                    $datas['image'] = changeUrl($datas['image']);
                }

                if (in_array($item['type'], [9, 10])) {
                    if (isset($datas['status']) && $datas['status']) {
                        if (isset($datas['start']) && isset($datas['end'])) {
                            $chat_time = $datas['end'] - $datas['start'];
                            $result[$key]['chat_time'] = changeTime($chat_time);
                        } else {
                            if ($datas['second']) {
                                $result[$key]['content'] .= changeTime($datas['second'] * 60);
                            } else {
                                $result[$key]['content'] .= '01:00';
                            }
                        }
                    } else {
                        $result[$key]['content'] .= ' 未接通';
                    }
                }

                $result[$key]['data'] = $datas;
            }

            $data['new'] = $result;

            $couple_a = $userid < $touserid ? $userid . ',' . $touserid : $touserid . ',' . $userid;
            $intimate = M('user_intimate')->where(['couple_a' => $couple_a])->getField('intimate');

            $data['users']['intimate'] = $intimate ?: 0;
        }

        // 消息撤回提示
        $ids = M('privatechat')->where(['userid' => $touserid, 'touserid' => $userid, 'status' => 3, 'isRead' => 0])->getField('id', true);
        if ($ids) {
            $data['recall'] = $ids;
            M('privatechat')->where(['id' => ['in', $ids]])->save(['isRead' => 1]);

            /*// 更新会话列表
            D('ChatLists')->changeLists($userid, $touserid);*/
        }

        $contain = $data;
        foreach ($contain['new'] as $k => $v) {
            $v['self'] = $v['self'] ? 0 : 1;
            $contain['new'][$k] = $v;
        }

        if (!empty($data['new']) || !empty($data['recall'])) {
            if (isset($result[0]) && $result[0]['single']) {
                $data = [];
            }
            $message1 = json_encode(['code' => 200, 'action' => 'Home/Privatechat/getNewMsg', 'data' => $contain]);
            $message2 = json_encode(['code' => 200, 'action' => 'Home/Privatechat/getNewMsg', 'data' => $data]);
        } else {
            $message1 = $message2 = json_encode(['code' => 400, 'action' => 'Home/Privatechat/getNewMsg', 'data' => []]);
        }

        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, $message1);   // 发送方
        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $userid, $message2);     // 接收方
    }

    // 聊天已读处理
    public function hadread()
    {
        $user_id = I('user_id');
        $touserid = I('touserid');

        try {
            M('privatechat')->where(['user_id' => $user_id, 'touserid' => $touserid])->setField('isRead', 1);

            // 更新会话列表
            D('ChatLists')->changeLists($user_id, $touserid);
        } catch (\Exception $e) {
            return json_encode(['code' => 201, 'msg' => $e->getMessage()]);
        }

        return json_encode(['code' => 200, 'msg' => 'success']);
    }

    // 从聊天列表删除对话
    public function delChat()
    {
        $uid = I('uid');
        $touid = I('touid');

        if (!$uid || !$touid) {
            echo json_encode(['code' => 201, 'msg' => '参数 uid 或 touid 有误']);
            exit();
        }

        $res = M('del_chat')->add(['uid' => $uid, 'to_uid' => $touid]);

        if ($res) {
            M('privatechat')->where(['userid' => $touid, 'touserid' => $uid])->save(['isRead' => 1, 'isCount' => 1]);

            // 更新会话列表
            D('ChatLists')->changeLists($uid, $touid, 'delete', 1);

            $this->getreadcount(json_encode(['user_id' => $uid]));

            echo json_encode(['code' => 200, 'msg' => 'success']);
            exit();
        } else {
            echo json_encode(['code' => 201, 'msg' => 'error']);
            exit();
        }
    }

    public function getcurl($url, $datas)
    {
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $datas,
            CURLOPT_HTTPHEADER => array(
                "Content-Type:application/x-www-form-urlencoded"
            ),
        ));

        $response = curl_exec($curl);

        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            return ['code' => 400, 'msg' => "cURL Error #:" . $err];
        } else {
            return ['code' => 200, 'data' => $response];
        }
    }

    //-----------------------------------------------------------------

    // 消息撤回
    public function recall()
    {
        $chat_id = I('chat_id');    # 聊天消息id
        $user_id = I('user_id');    # 用户id

        if (!$chat_id || !$user_id) exit(json_encode(['code' => 201, 'msg' => '操作有误']));

        $data = M('privatechat')->where(['id' => $chat_id])->find();
        $touserid = $data['touserid'];

        if (!$data) exit(json_encode(['code' => 201, 'msg' => '消息不存在']));
        if ($data['userid'] != $user_id) exit(json_encode(['code' => 201, 'msg' => '无权操作']));
        if (in_array($data['status'], [1, 3])) exit(json_encode(['code' => 201, 'msg' => '操作有误']));
        if ($data['type'] == 5) exit(json_encode(['code' => 201, 'msg' => '红包消息无法撤回']));
        if ((strtotime($data['addtime']) + 30) <= time()) exit(json_encode(['code' => 201, 'msg' => '消息发出30秒后无法撤回']));

        try {
            M('privatechat')->where(['id' => $chat_id])->save(['status' => 3, 'type' => -1, 'isRead' => 0]);
        } catch (Exception $e) {
            exit(json_encode(['code' => 201, 'msg' => $e->getMessage()]));
        }

        // 更新会话列表
        D('ChatLists')->changeLists($user_id, $touserid, 'recall');

        /*// 清除聊天缓存
        S("getMsgList$user_id&$touserid",null);
        S("getMsgList$touserid&$user_id",null);*/

        $this->getNewMsg(json_encode(['userid' => $data['touserid'], 'touserid' => $user_id]));
        $this->getOtherList(json_encode(['userid' => $data['touserid'], 'count' => '', 'type' => '']));

        exit(json_encode(['code' => 200, 'msg' => '已撤回']));
    }

    // 消息删除
    public function delete()
    {
        $chat_id = I('chat_id');    # 消息id
        $user_id = I('user_id');    # 用户id
        $to_user = I('to_user');    # 用户id

        if (!$chat_id && $to_user) {
            $data = M('privatechat')->where(['userid' => $user_id, 'touserid' => $to_user, 'status' => ['in', [-1,0,2]]])->select();

            $conDel = [];
            $conUpdate = [];
            foreach ($data as $key => $item) {
                if ($item['status'] == 2) {
                    $conDel[] = $item['id'];
                } else {
                    $conUpdate[] = $item['id'];
                }
            }

            if ($conDel) {
                M('privatechat')->where(['id' => ['in', $conDel]])->delete();
            }

            if ($conUpdate) {
                M('privatechat')->where(['id' => ['in', $conUpdate]])->setField('status', 1);
            }

            $data = M('privatechat')->where(['userid' => $to_user, 'touserid' => $user_id, 'status' => ['in', [-1,0,1]]])->select();

            $conDel = [];
            $conUpdate = [];
            foreach ($data as $key => $item) {
                if ($item['status'] == 1) {
                    $conDel[] = $item['id'];
                } else {
                    $conUpdate[] = $item['id'];
                }
            }

            if ($conDel) {
                M('privatechat')->where(['id' => ['in', $conDel]])->delete();
            }

            if ($conUpdate) {
                M('privatechat')->where(['id' => ['in', $conUpdate]])->setField('status', 2);
            }

            $delChat = M('del_chat')->where(['uid' => $user_id, 'to_uid' => $to_user])->find();

            if (!$delChat) {
                M('del_chat')->add(['uid' => $user_id, 'to_uid' => $to_user]);
            }
    
            // 撤回消息
            M('privatechat')->where(['type' => -1, 'userid' => $user_id, 'touserid' => $to_user, 'status' => 3])->delete();

            $msg = '已清空';

            // 更新会话列表
            D('ChatLists')->changeLists($user_id, $to_user, 'delete_all');

        } else if ($chat_id && !$to_user) {
            $chat_id = explode(',', $chat_id);

            //$data = M('privatechat')->where(['id' => $chat_id[0]])->find();

            $data = M('privatechat')->where(['id' => ['in', $chat_id]])->select();

            $conDel = [];
            $status_1 = [];
            $status_2 = [];
            foreach ($data as $key => $item) {
                if ($item['userid'] == $user_id) {
                    if ($item['status'] == 2) {
                        $conDel[] = $item['id'];
                    } else {
                        $status_1[] = $item['id'];
                    }
                } else {
                    if ($item['status'] == 1) {
                        $conDel[] = $item['id'];
                    } else {
                        $status_2[] = $item['id'];
                    }
                }
            }

            if ($conDel) {
                M('privatechat')->where(['id' => ['in', $conDel]])->delete();
            }

            if ($status_1) {
                M('privatechat')->where(['id' => ['in', $status_1]])->setField('status', 1);
            }

            if ($status_2) {
                M('privatechat')->where(['id' => ['in', $status_2]])->setField('status', 2);
            }

            $msg = '已删除';

            if ($data[0]) {
                $to_user = $data[0]['userid'] == $user_id ? $data[0]['touserid'] : $data[0]['userid'];

                // 更新会话列表
                D('ChatLists')->changeLists($user_id, $to_user, 'delete_one');
            }


            /*if (!$data) exit(json_encode(['code' => 201, 'msg' => '消息不存在']));

            if ($data['userid'] == $user_id) { # 发送方删除
                if (in_array($data['status'], [1, 3])) exit(json_encode(['code' => 201, 'msg' => '无权操作']));
                $status = 1;
            } else if ($data['touserid'] == $user_id) { # 接收方删除
                if (in_array($data['status'], [2, 3])) exit(json_encode(['code' => 201, 'msg' => '无权操作']));
                $status = 2;
            } else {
                exit(json_encode(['code' => 201, 'msg' => '无权操作']));
            }

            M('privatechat')->where(['id' => ['in', $chat_id]])->save(['status' => $status]);*/
        }

        // 清除聊天缓存
        S("getMsgList$user_id&$to_user",null);
        S("getMsgList$to_user&$user_id",null);

        exit(json_encode(['code' => 200, 'msg' => $msg]));
    }

    // 领取红包
    public function receive()
    {
        $chat_id = I('chat_id');    # 聊天消息id
        $user_id = I('user_id');    # 用户id

        if (!$chat_id || !$user_id) exit(json_encode(['code' => 201, 'msg' => '操作有误']));

        $data = M('privatechat')->where(['id' => $chat_id, 'type' => ['in', [5, 7]], 'status' => ['not in', [-1, 3]], 'state' => 0])->find();

        if (!$data) exit(json_encode(['code' => 201, 'msg' => '红包消息不存在']));

        if ($data['touserid'] != $user_id) exit(json_encode(['code' => 201, 'msg' => '无权操作']));

        // 红包金额
        $money = M('order_common')->where(['data' => '{"id":' . $chat_id . '}'])->getField('money');
        $name = M('user')->where(['id' => $data['userid']])->getField('name');
        $touser_name = M('user')->where(['id' => $data['touserid']])->getField('name');

        // 开启事务
        M()->startTrans();
        try {
            // 红包状态改变
            M('privatechat')->where(['id' => $chat_id])->save(['state' => 1]);
            if ($data['type'] == 7) { //现金红包
                $rate = M('config_system')->where(['title' => 'rate'])->getField('content');
                $money = $money * $rate;
            }
            M('user')->where(['id' => $user_id])->setInc('volley', $money);
            M('volley_desc')->add(['user_id' => $user_id, 'content' => '领取红包', 'price' => $money, 'types' => 1, 'time' => time()]);

            // 添加聊天
            $id = M('privatechat')->add([
                "userid" => $data['touserid'],
                "touserid" => $data['userid'],
                "type" => -1,
                "content" => '领取红包',
                "data" => json_encode([
                    'chat_id' => $chat_id,
                    'userid' => $data['userid'],
                    'user_name' => $name,
                    'touserid' => $data['touserid'],
                    'touser_name' => $touser_name,
                    'type' => $data['type']
                ]),
                "state" => 1,
            ]);

            M()->commit();//提交
        } catch (\Exception $e) {
            M()->rollback();//回滚
            exit(json_encode(['code' => 201, 'msg' => $e->getMessage()]));
        }

        exit(json_encode(['code' => 200, 'msg' => '领取成功']));
    }

    // 红包详情
    public function details()
    {
        $chat_id = I('chat_id');    # 聊天消息id

        if (!$chat_id) exit(json_encode(['code' => 201, 'msg' => '操作有误']));

        $data = M('privatechat')
            ->field('id, userid, content, state')
            ->where(['id' => $chat_id, 'type' => ['in', [5, 7]], 'status' => ['not in', [-1, 3]]])
            ->find();

        if (!$data) exit(json_encode(['code' => 201, 'msg' => '红包消息不存在']));

        $user = M('user')->field('name, head_100 head')->where(['id' => $data['userid']])->find();

        // 红包金额
        $money = M('order_common')->where(['data' => '{"id":' . $chat_id . '}'])->getField('money');

        $data['money'] = $money;
        $data = array_merge($data, $user);

        exit(json_encode(['code' => 200, 'data' => $data]));
    }

    //-----------------------------------------------------------------

    // 发起语音通话请求
    public function toRequest()
    {
        $user_id = I('user_id');
        $another_id = I('another_id');
        $channel = I('channel');        // 加入的频道
        $types = I('types');            // 1语音 | 2视频
        $orderid = I('orderid');

        $user = M('user')->field('id, name')->where(['id' => $user_id])->find();

        $message = json_encode([
            'code' => 200,
            'action' => 'Home/Privatechat/toRequest',
            'data' => [
                'user_id' => $user_id,
                'another_id' => $another_id,
                'types' => $types,
                'channel' => $channel,
                'name' => $user['name'],
                'orderid' => $orderid
            ]
        ]);

        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user_id, $message);
    }

    // 语音通话请求结果
    public function returnRequest()
    {
        $user_id = I('user_id');
        $another_id = I('another_id');
        $channel = I('channel');        // 加入的频道
        $status = I('status');          // 0取消 | 1接听 | 2无权限
        $types = I('types');            // 1语音 | 2视频
        $orderid = I('orderid');

        $user = M('user')->where(['id' => $user_id])->find();

        if ($orderid) {
            $order = M('order_common')->master(true)->find($orderid);

            if ($order) {
                $data = json_decode($order['data'], true);

                if (isset($data['start'])) {
                    $data['end'] = time();
                } else {
                    $data['start'] = time();
                }

                $data_json = json_encode($data);

                M('order_common')->where(['id' => $orderid])->save(['data' => $data_json]);

                //$chat = M('privatechat')->where(['data' => ['like', '{"orderid":"' . $orderid . '"%']])->find();
                $chat = M('privatechat')->master(true)->where(['order_id' => $orderid])->find();

                if ($chat) {
                    $data = json_decode($chat['data'], true);

                    if (isset($data['start'])) {
                        $data['end'] = time();
                    } else {
                        $data['start'] = time();

                        $data['status'] = $status;
                    }

                    $data_json = json_encode($data);

                    M('privatechat')->where(['id' => $chat['id']])->save(['data' => $data_json]);
                    $chat['data'] = $data_json;
                    // 更新会话列表
                    D('ChatLists')->changeLists($chat['userid'], $chat['touserid']);
                }
            }
        }

        $message = json_encode([
            'code' => 200,
            'action' => 'Home/Privatechat/returnRequest',
            'data' => [
                'user_id' => $user_id,
                'another_id' => $another_id,
                'types' => $types,
                'channel' => $channel,
                'name' => $user['name'],
                //'status' => in_array($status, [0,1,2,3,4]) ? $status : 1
                'status' => $status
            ]
        ]);

        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user_id, $message);

        if (!$status) {
            /*$order = M('order_common')->where(['id' => $orderid])->find();
            $datas = json_decode($order['data']);

            $free_use = $datas['free_use'] ?: 0;

            if ($free_use) {
                $content = "对方使用免费时长{$free_use}分钟";
                $contain = ["userid" => $another_id, "touserid" => $user_id, "type" => -1, 'single' => 1, "content" => $content, 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];

                M('privatechat')->add($contain);
            }*/


            $this->pushNewMsg($chat);
            $this->getOtherList(json_encode(['userid' => $another_id, 'count' => '', 'type' => '']));
            // $this->getNewMsg(json_encode(['userid' => $another_id, 'touserid' => $user_id, 'type' => $types + 8]));
            // $this->getNewMsg(json_encode(['userid' => $user_id, 'touserid' => $another_id, 'type' => $types + 8]));

        }/* else if ($status == 1 && $orderid) {
            $this->getcurl(fullPath('api/member/createMic'), 'user_id=' . $order['user_id'] . '&orderid=' . $orderid);
        }*/
    }

    //-----------------------------------------------------------------

    // 聊天图片焚毁
    public function burnImg()
    {
        $id = I('id');
        $user_id = I('user_id');   // 发送者id
        $touserid = I('touserid'); // 接受者id

        $result = M('privatechat')->where(['id' => $id, 'touserid' => $touserid, 'type' => 1])->setField('is_burn', -1);

        if ($result) {
            $message = json_encode(['code' => 200, 'action' => 'Home/Privatechat/burnImg', 'msg' => '焚毁成功', 'data' => ['id' => $id]]);

            Gateway::sendToUid([getenv('SOCKET_PREFIX') . $user_id, getenv('SOCKET_PREFIX') . $touserid], $message);   // 实时显示图片是否已焚毁
        } else {
            $message = json_encode(['code' => 400, 'action' => 'Home/Privatechat/burnImg', 'msg' => '焚毁失败']);

            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user_id, $message);   // 实时显示图片是否已焚毁
        }
    }

    //-----------------------------------------------------------------

    public function allRead()
    {
        $user_id = I('user_id');

        M('privatechat')->where(['touserid' => $user_id, 'isRead' => 0])->save(['isRead' => 1, 'sound_tip' => 1]);

        exit(json_encode(['code' => 200, 'msg' => '设置成功']));
    }

    // 置顶聊天
    public function topChat()
    {
        $types = I('types'); // 1私聊|2群聊
        $uid = I('uid');
        $touid = I('touid');

        $where = ['types' => $types, 'uid' => $uid, 'to_uid' => $touid];

        if (!$touid || !$uid) {
            exit(json_encode(['code' => 400, 'result' => '缺少参数']));
        }
        $res = M('top_chat')->where($where)->find();

        if ($res) {
            M('top_chat')->where($where)->delete();

            $is_top = 0;
        } else {
            M('top_chat')->add($where);

            $is_top = 1;
        }

        // 更新会话列表
        D('ChatLists')->changeLists($uid, $touid, 'top', $is_top);

        exit(json_encode(['code' => 200, 'msg' => '成功']));
    }

    public function forward()
    {
        $chat_id = intval(I('chat_id'));
        $user_id = intval(I('user_id'));
        $to_user = intval(I('to_user'));

        if (!$user_id || !$to_user) {
            exit(json_encode(['code' => 400, 'msg' => '操作失败']));
        }

        if ($user_id == $to_user) {
            exit(json_encode(['code' => 400, 'msg' => '无法转发给自己']));
        }

        $chat = M('privatechat')->where(['id' => $chat_id])->find();

        if (!$chat) {
            exit(json_encode(['code' => 400, 'msg' => '消息不存在']));
        }

        if ($chat['userid'] != $user_id && $chat['touserid'] != $user_id) {
            exit(json_encode(['code' => 400, 'msg' => '操作失败']));
        }

        $response = $this->addTalk($user_id, $to_user, $chat['type'], $chat['content'], $chat['second']);

        if ($response) {
            return $response;
        } else {
            exit(json_encode(['code' => 200, 'msg' => '转发成功']));
        }
    }

    //----------------------------------------------------
    
    public function greet()
    {
        exit;

        $config = M('config_system')->where(['category' => ['in', ['greet', 'kefu']]])->getField('title, content');
        
        $kefu = intval($config['id']);
        
        if ($config['greet_newest']) {
            $space = $config['greet_newest'] + 60 * $config['greet_space'];
            if ($space > time()) {
                exit;
            }
        }
        
        if ($config['greet_switch'] + 0) {
            M('config_system')->where(['title' => 'greet_newest'])->save(['content' => time()]);
            
            $now = date('H');
            
            if ($config['greet_start'] <= $now && $now < $config['greet_end']) {
                
                // 女性向男性打招呼
                // 男性
                $where = $whereOr = [
                    //'id' => ['neq', $kefu],
                    'id' => ['gt', '5555555'],
                    'sex' => '男',
                    'role' => 0,
                    'is_banned' => 0,
                    'proxy' => 0,
                    'greet_receive_count' => ['lt', $config['greet_male_receive_max']],
                    'yqr' => ['eq', '']
                ];
                
                $where['is_online'] = 1;
                $last_login_date = date('Y-m-d H:i:s', strtotime(date('Y-m-d')));
                $where['last_login_datetime'] = ['gt', $last_login_date];
                $whereOr['is_online'] = 0;
                
                //$whereOr['last_login_datetime'] = ['gt', date('Y-m-d H:i:s', strtotime('-1 day'))];
                $whereOr['last_login_datetime'] = ['gt', date('Y-m-d H:i:s', (time() - 14400))];
                
                $males = M('user')->where($where)->order('tycoon desc, volley desc, noble_grade desc')->select();
                
                if ($males) {
                    $contents = M('privatechat_zhaohu')->where(['types' => 2, 'is_hidden' => 0])->cache(86400)->getField('content', true);
                    
                    if ($contents) {
                        $males_ids = array_column($males, 'id');
                        
                        $where = [
                            //'id' => ['neq', $kefu],
                            'id' => ['gt', '5555555'],
                            'sex' => '女',
                            'is_banned' => 0,
                            'is_identity_authentication' => 2,
                            'proxy' => 0,
                            'greet_count' => ['lt', $config['greet_female_max']]
                        ];
                        /*if (!$config['greet_offline']) {
                            $where['last_login_datetime'] = ['gt', date('Y-m-d H:i:s', strtotime('-2 day'))];
                        }*/
                        
                        $females = M('user')->field('id, voice, voice_time, greet_count, greet_time')->where($where)->order('role asc, is_online desc, charm_value desc, shouyi desc, following desc, zan desc, proxy desc')->select();
                        
                        if ($females) {
                            $start = strtotime(date('Ymd')) - 86400 * 4;
                            $greetRecords = M('greet_records')->where(['user_id' => ['in', $males_ids], 'create_time' => ['gt', $start]])->select();
                            
                            $greetContain = [];
                            foreach ($greetRecords as $key => $item) {
                                $greetContain[] = $item['user_id'] . '+' . $item['to_user'];
                            }
                            
                            $females_ids = array_column($females, 'id');
                            $userImgs = M('user_img')->where(['types' => 1, 'user_id' => ['in', $females_ids], 'packet' => 0, 'is_auth' => 0, 'is_avatar' => 0, 'status' => 1])->order('rand()')->getField('user_id, picthumb');
                            //$userDymanics = M('dymanic')->where(['type' => 0, 'userid' => ['in', $females_ids], 'shenhe' => 1])->getField('userid, dy_id, content, sumbImage,video, cover');
                            $userDymanics = [];
                            $start_time = strtotime(date('Y-m-d'));
                            $end_time = $start_time + 86399;
                            $greet_count_day = M('greet_records')->where(['user_id' => ['in', $males_ids], 'create_time' => ['between', [$start_time, $end_time]]])->group('user_id')->getField('user_id, count(*) count');
                            
                            $insert = [];
                            $update_male = [];
                            $update_female = [];
                            $current_time = time();
                            $greet_offline_max = explode(',', $config['greet_offline_max']);
                            foreach ($males as $key => $item) {
                                if ($item['id'] != $kefu) {
                                    if (!$item['is_online'] && isset($greet_count_day[$item['id']]) && $greet_count_day[$item['id']] >= $greet_offline_max[0]) {
                                        continue;
                                    } else {
                                        $push_count = 0;
                                        foreach ($females as $m => $n) {
                                            if ($n['id'] == $kefu) {
                                                continue;
                                            }

                                            if ($push_count < $config['greet_female_count']) {
                                                if ($n['greet_count'] < $config['greet_female_max']) {
                                                    $merge = $item['id'] . '+' . $n['id'];
                                                    if (!in_array($merge, $greetContain)) {
                                                        $greetContain[] = $merge;
                                                        $insert[] = ['user_id' => $item['id'], 'to_user' => $n['id'], 'create_time' => $current_time];

                                                        //M('greet_records')->add(['user_id' => $item['id'], 'to_user' => $n['id'], 'create_time' => $current_time]);

                                                        $females[$m]['greet_count'] = $n['greet_count'] = $n['greet_count'] + 1;

                                                        if (isset($update_female[$n['id']])) {
                                                            $update_female[$n['id']]['greet_count'] = $n['greet_count'];
                                                            $update_female[$n['id']]['greet_time'] = $current_time;
                                                        } else {
                                                            $update_female[$n['id']] = ['id' => $n['id'], 'greet_count' => $n['greet_count'], 'greet_time' => $current_time];
                                                        }

                                                        $item['greet_receive_count'] += 1;
                                                        if (isset($update_male[$item['id']])) {
                                                            $update_male[$item['id']]['greet_receive_count'] = $item['greet_receive_count'];
                                                            $update_male[$item['id']]['greet_receive_time'] = $current_time;
                                                        } else {
                                                            $update_male[$item['id']] = ['id' => $item['id'], 'greet_receive_count' => $item['greet_receive_count'], 'greet_receive_time' => $current_time];
                                                        }

                                                        $push_count += 1;

                                                        $rand = mt_rand(0, count($contents) - 1);
                                                        $content = $contents[$rand];
                                                        $chat_type = 0;
                                                        $chat_second = 0;
                                                        $chat_datas = '';

                                                        $chat_contain = ['0', '1', '2', '11'];

                                                        //$chat_rand = mt_rand(0, 2);
                                                        $chat_rand = 0;
                                                        if ($chat_contain[$chat_rand] == 1) {
                                                            if (isset($userImgs[$n['id']])) {
                                                                $userImg = json_decode($userImgs[$n['id']], true);

                                                                if (isset($userImg[0])) {
                                                                    $chat_type = 1;
                                                                    $content = $userImg[0];
                                                                }
                                                            }
                                                        } else if ($chat_contain[$chat_rand] == 2) {
                                                            if ($n['voice']) {
                                                                $chat_type = 2;
                                                                $content = $n['voice'];
                                                                $chat_second = $n['voice_time'];
                                                            }
                                                        } else if ($chat_contain[$chat_rand] == 11) {
                                                            if (isset($userDymanics[$n['id']])) {
                                                                $chat_type = 11;
                                                                $content = '[动态]';

                                                                $chat_datas = [
                                                                    'dy_id' => $userDymanics[$n['id']]['dy_id'],
                                                                    'content' => $userDymanics[$n['id']]['content'],
                                                                ];

                                                                if ($userDymanics[$n['id']]['video']) {
                                                                    $chat_datas['video'] = $userDymanics[$n['id']]['video'];
                                                                    $chat_datas['cover'] = $userDymanics[$n['id']]['cover'];
                                                                } else {
                                                                    $chat_datas['images'] = $userDymanics[$n['id']]['sumbImage'];
                                                                }

                                                                $chat_datas = json_encode($chat_datas, JSON_UNESCAPED_UNICODE);
                                                            }
                                                        }

                                                        $data = [
                                                            'userid' => $n['id'],
                                                            'touserid' => $item['id'],
                                                            'type' => $chat_type,
                                                            'content' => $content,
                                                            'second' => $chat_second,
                                                            'data' => $chat_datas,
                                                            'timing' => 1,
                                                            'greet' => 1,
                                                            'system_greet' => 1,
                                                        ];

                                                        usleep(5000);

                                                        $this->addTalk($n['id'], $item['id'], $chat_type, $content, $chat_second, $chat_datas, 1, 1, 1);
                                                    }
                                                }
                                            } else {
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            
                            if ($insert) {
                                $GreetRecords = M("greet_records");
                                $GreetRecords->addAll($insert);
                            }
                            
                            
                            if ($update_female) {
                                $User = M("User");
                                foreach ($update_female as $key => $item) {
                                    $User->save($item);
                                }
                            }
                            
                            if ($update_male) {
                                $User = M("User");
                                foreach ($update_male as $key => $item) {
                                    $User->save($item);
                                }
                            }
                        }
                    }
                }
                
                sleep(3);
                
                // 男性向女性打招呼
                // 女性
                $where = $whereOr = [
                    //'id' => ['neq', $kefu],
                    'id' => ['gt', '5555555'],
                    'sex' => '女',
                    'role' => 0,
                    'is_banned' => 0,
                    'is_identity_authentication' => 2,
                    'proxy' => 0,
                    'greet_receive_count' => ['lt', $config['greet_female_receive_max']]
                ];
                
                $where['is_online'] = 1;
                $last_login_date = date('Y-m-d H:i:s', strtotime(date('Y-m-d')));
                $where['last_login_datetime'] = ['gt', $last_login_date];
                $whereOr['is_online'] = 0;
                //$whereOr['last_login_datetime'] = ['gt', date('Y-m-d H:i:s', strtotime('-1 day'))];
                $whereOr['last_login_datetime'] = ['gt', date('Y-m-d H:i:s', (time() - 14400))];
                
                $females = M('user')->where($where)->order('score desc, following desc, zan desc, charm_value desc')->select();
                
                if ($females) {
                    $contents = M('privatechat_zhaohu')->where(['types' => 1, 'is_hidden' => 0])->cache(86400)->getField('content', true);
                    
                    if ($contents) {
                        $females_ids = array_column($females, 'id');
                        
                        $where = [
                            //'id' => ['neq', $kefu],
                            'id' => ['gt', '5555555'],
                            'sex' => '男',
                            'is_banned' => 0,
                            'proxy' => 0,
                            'greet_count' => ['lt', $config['greet_male_max']],
                            'yqr' => ['eq', '']
                        ];
                        
                        /*if (!$config['greet_offline']) {
                            $where['last_login_datetime'] = ['gt', date('Y-m-d H:i:s', strtotime('-2 day'))];
                        }*/
                        
                        $males = M('user')->where($where)->order('is_online desc, noble_grade desc, volley desc, tycoon desc')->select();
                        
                        if ($males) {
                            
                            $start = strtotime(date('Ymd')) - 86400 * 5;
                            $greetRecords = M('greet_records')->where(['user_id' => ['in', $females_ids], 'create_time' => ['gt', $start]])->select();
                            
                            $greetContain = [];
                            foreach ($greetRecords as $key => $item) {
                                $greetContain[] = $item['user_id'] . '+' . $item['to_user'];
                            }
                            
                            $start_time = strtotime(date('Y-m-d'));
                            $end_time = $start_time + 86399;
                            $greet_count_day = M('greet_records')->where(['user_id' => ['in', $females_ids], 'create_time' => ['between', [$start_time, $end_time]]])->group('user_id')->getField('user_id, count(*) count');
                            
                            $insert = [];
                            $update_male = [];
                            $update_female = [];
                            $current_time = time();
                            $greet_offline_max = explode(',', $config['greet_offline_max']);
                            foreach ($females as $key => $item) {
                                if ($item['id'] != $kefu) {
                                    if (!$item['is_online'] && isset($greet_count_day[$item['id']]) && $greet_count_day[$item['id']] >= $greet_offline_max[0]) {
                                        continue;
                                    } else {
                                        $push_count = 0;
                                        foreach ($males as $m => $n) {
                                            if ($n['id'] == $kefu) {
                                                continue;
                                            }

                                            if ($push_count < $config['greet_male_count']) {
                                                if ($n['greet_count'] < $config['greet_male_max']) {
                                                    $merge = $item['id'] . '+' . $n['id'];
                                                    if (!in_array($merge, $greetContain)) {
                                                        $greetContain[] = $merge;
                                                        $insert[] = ['user_id' => $item['id'], 'to_user' => $n['id'], 'create_time' => $current_time];

                                                        //M('greet_records')->add(['user_id' => $item['id'], 'to_user' => $n['id'], 'create_time' => $current_time]);

                                                        $males[$m]['greet_count'] = $n['greet_count'] = $n['greet_count'] + 1;

                                                        if (isset($update_male[$n['id']])) {
                                                            $update_male[$n['id']]['greet_count'] = $n['greet_count'];
                                                            $update_male[$n['id']]['greet_time'] = $current_time;
                                                        } else {
                                                            $update_male[$n['id']] = ['id' => $n['id'], 'greet_count' => $n['greet_count'], 'greet_time' => $current_time];
                                                        }

                                                        $item['greet_receive_count'] += 1;
                                                        if (isset($update_female[$item['id']])) {
                                                            $update_female[$item['id']]['greet_receive_count'] = $item['greet_receive_count'];
                                                            $update_female[$item['id']]['greet_receive_time'] = $current_time;
                                                        } else {
                                                            $update_female[$item['id']] = ['id' => $item['id'], 'greet_receive_count' => $item['greet_receive_count'], 'greet_receive_time' => $current_time];
                                                        }

                                                        $push_count += 1;

                                                        $rand = mt_rand(0, count($contents) - 1);

                                                        $data = [
                                                            'userid' => $n['id'],
                                                            'touserid' => $item['id'],
                                                            'content' => $contents[$rand],
                                                            'timing' => 1,
                                                            'greet' => 1,
                                                            'system_greet' => 1,
                                                        ];

                                                        usleep(5000);

                                                        $this->addTalk($n['id'], $item['id'], 0, $content, 0, '', 1, 1, 1);
                                                    }
                                                }
                                            } else {
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            
                            if ($insert) {
                                $GreetRecords = M("greet_records");
                                $GreetRecords->addAll($insert);
                            }
                            
                            if ($update_male) {
                                $User = M("User");
                                foreach ($update_male as $key => $item) {
                                    $User->save($item);
                                }
                            }
                            
                            if ($update_female) {
                                $User = M("User");
                                foreach ($update_female as $key => $item) {
                                    $User->save($item);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public function loginGreet($user_id)
    {
        exit;

        $config = M('config_system')->where(['category' => ['in', ['kefu']]])->getField('title, content');
    
        $kefu = intval($config['id']);
        
        if ($kefu != $user_id) {
            $user = M('user')->field('id, sex, is_online, last_login_datetime, yqr')->where(['id' => $user_id])->find();
    
            if ($user['sex'] == '男' && $user['yqr']) {
                exit;
            }
            
            if ($user['is_online'] && (strtotime($user['last_login_datetime']) + 10) > time()) {
                $kefu = M('config_system')->where(['title' => 'id'])->getField('content');
                $kefu = intval($kefu);
        
                $sex = $user['sex'] == '男' ? '女' : '男';
                $where = ['id' => ['neq', $kefu], 'sex' => $sex, 'is_online' => 1];
    
                if ($user['sex'] == '女') {
                    $where['yqr'] = ['eq', ''];
                }
        
                $count = mt_rand(20, 30);
        
                $ids = M('user')->where($where)->order('rand()')->limit($count)->getField('id', true);
        
                $types = $user['sex'] == '男' ? 2 : 1;
        
                $contents = M('privatechat_zhaohu')->where(['types' => $types, 'is_hidden' => 0])->getField('content', true);
        
                if ($contents) {
                    foreach ($ids as $item) {
                        $contentsCount = count($contents) - 1;
                        $content = $contents[mt_rand(0, $contentsCount)];
                
                        $this->addTalk($item, $user_id, 0, $content, 0, '', 1, 0, 1, 1);
                    }
                }
            }
        }
    }

    // 今日缘分
    public function fatebak($id, $user_id)
    {
        $ids = explode(',', $id);
        
        $user = M('user')->field('id, sex')->where(['id' => $user_id])->find();
        $types = $user['sex'] == '男' ? 1 : 2;
        
        $contents = M('privatechat_default')->where(['types' => $types, 'channel' => 2, 'user_id' => ['in', [0, $user_id]]])->getField('content', true);
        if (!$contents) {
            $contents = M('privatechat_zhaohu')->where(['types' => $types, 'is_hidden' => 0])->getField('content', true);
        }

        M('user')->where(['id' => $user_id])->setField('zhaohu_time', time());
        
        if ($contents) {
            // 心动数+1
            M('user')->where(['id' => ['in', $ids]])->setInc('heart');
            
            foreach ($ids as $item) {
                $content = $contents[mt_rand(0, count($contents) - 1)];
                $this->addTalk($user_id, $item, 0, $content, 0, '', 1, 0, 0, 0, 0, 1);
            }
        }
    }



    public function fate($id, $user_id, $word_id='', $window=0)
    {
        $ids = explode(',', $id);

        // if(sizeof($ids) == 1){
        //     $fields = $user_id < $id ? 'couple_a' : 'couple_b';
        //     $intimate = M('user_intimate')->where([$fields=>$user_id.','.$id])->getField('intimate');
        //     if($intimate && $intimate>0){
        //         exit(json_encode(['code'=>400, 'msg'=>'你们已经有亲密度了，不能向对方打招呼']));
        //     }
        // }

        if($window == 0){
            $result = D('Privatechat')->checkGreet($user_id);
            if ($result && $result['code'] == 400) {
                exit(json_encode($result));
            }
        }

        $seeRecord = M('see_record');

        
        if ($ids) {
            if ($word_id) {
                $word_ids = explode(',', $word_id);

                $user = M('user')->field('id, sex')->where(['id' => $user_id])->find();
                $types = $user['sex'] == '男' ? 1 : 2;

                $words = M('privatechat_greet')->where(['id' => ['in', $word_id], 'user_id' => $user_id, 'status' => 1])->getField('id, channel, content, voice_time');

                M('user')->where(['id' => $user_id])->setField('zhaohu_time', time());

                if ($words) {
                    // 心动数+1
                    M('user')->where(['id' => ['in', $ids]])->setInc('heart');

                    $visitors = $seeRecord->where(['user_id' => $user_id, 'the_user' => ['in', $ids]])->getField('the_user, id');

                    $insert = [];
                    $update = [];

                    //$type = $word['channel'] == 1 ? 2 : 0;
                    foreach ($ids as $item) {
                        if (isset($visitors[$item])) {
                            $update[] = ['id' => $visitors[$item], 'is_read' => 0, 'addtime' => date('Y-m-d H:i:s')];
                        } else {
                            $insert[] = ['user_id' => $user_id, 'the_user' => $item];
                        }

                        $rand = mt_rand(0, count($word_ids) - 1);
                        $word = $words[$word_ids[$rand]];
                        $type = $word['channel'] == 1 ? 2 : 0;
                        $second = $word['voice_time'];
                        $this->addTalk($user_id, $item, $type, $word['content'], $second, '', 1, 0, 0, 0, 0, 1);
                    }

                    if ($insert) {
                        $seeRecord->addAll($insert);
                    }

                    foreach ($update as $key => $item) {
                        $seeRecord->save($item);
                    }
                }
            }
        }
        
    }

    public function clearfirst()
    {
        $user_id = I('user_id');
        $userInfo = M('user')->where(['id'=>$user_id])->field('id, sex')->cache(86400)->find();
        if($userInfo['sex'] == '女'){
            $sql1 = "update chat_lists set user_delete=1 WHERE user_id = $user_id and user_delete = 0 and user_first = 1";
            $sql2 = "update chat_lists set another_delete=1 WHERE another_id = $user_id and another_delete = 0 and another_first = 1";
        }else{
            $sql1 = "update chat_lists set user_delete=1 WHERE user_id = $user_id and user_delete = 0 and another_first = 1";
            $sql2 = "update chat_lists set another_delete=1 WHERE another_id = $user_id and another_delete = 0 and user_first = 1";
        }
        $datasql1 = M()->execute($sql1);
        $datasql2 = M()->execute($sql2);
        exit(json_encode(['code' => 200, 'msg' => '清理成功']));
    }

}
